I want to make use of functions to get the full path and directory name of a script.
For this I made two functions :
function _jb-get-script-path ()
{
#returns full path to current working directory
# + path to the script + name of the script file
return $PWD/${0#./*}
}
function _jb-get-script-dirname ()
{
return ${(_jb-get-script-path)##*/}
}
as $(_jb-get-script-path) should be replaced by the result of the function called.
However, I get an error: ${(_jb-get-script-path)##*/}: bad substitution
therefore i tried another way :
function _jb-get-script-path ()
{
return $PWD/${0#./*}
}
function _jb-get-script-dirname ()
{
local temp=$(_jb-get-script-path);
return ${temp##*/}
}
but in this case, the first functions causes an error : numeric argument required. I tried to run local temp=$(_jb-get-script-path $0) in case the $0 wasn't provided through function call (or i don't really know why) but it didn't change anything
I don't want to copy the content of the second fonction as i don't want to replicate code for no good reason.
If you know why those errors happen, I really would like to know why, and of course, if you have a better solution, i'd gladely hear it. But I'm really interessed in the resolution of this problem.
You need to use echo instead of return which is used for returning a numeric status:
_jb-get-script-path() {
#returns full path to current working directory
# + path to the script + name of the script file
echo "$PWD/${0#./*}"
}
_jb-get-script-dirname() {
local p="$(_jb-get-script-path)"
echo "${p##*/}"
}
_jb-get-script-dirname
Related
I am trying to lock a file with the flock function but I am not able to do it. I work with Laravel 8 and Storage Class.
The code is as follows:
$disk = Storage::disk('communication');
$file_name = 'received.json';
$file_exists = $disk->exists($file_name);
if($file_exists){
flock($disk->get($file_name), LOCK_EX);
...
}
The problem I'm having is that when I invoke the get() function on the file path, it returns the contents of the file (a string), which causes the following error:
flock() expects parameter 1 to be resource, string given
I need to know how to get file as a resource and not the content of the file.
Could someone help me and tell me how to do it?
Thank you very much in advance.
You can use Storage::readStream() method
if($file_exists){
$stream=Storage::disk('communication')->readStream($file_name);
flock($stream, LOCK_EX);
}
As per php doc
flock(resource $stream, int $operation, int &$would_block = null): bool
First param needed stream.flock() allows you to perform a simple
reader/writer model which can be used on virtually every platform
(including most Unix derivatives and even Windows).
Ref:https://www.php.net/manual/en/function.flock.php
I have a script with many other scripts sourced. Each script sourced have a function.
One of my function need to stop according to a if statement. I tried continue, break, throw, evrything I saw on internet but either my main script completely end or my function continue.
Function code:
function AutoIndus-DeployUser($path){
$yaml=Get-Content $path | ?{!$_.StartsWith("#")}
$UsersPwd=$false
$user="";$password="";$groups="";$description=""; $options=""
$yaml | %{
if (($_-match "}") -and ($UsersPwd -eq $true)){Write-Host "function should stop"; return}
*actions*
}
}
Main script:
#functions list and link to extern scripts
Get-ChildItem -Path $PSScriptRoot\functions\ | %{$script=$_.Name; . $PSScriptRoot\functions\$script}
myfunction-doesnotwork
*some code*
Edit: I saw that return should stop the function without stoping the rest of the script, unfortunatly it does not stop anything at all:
Output:
Config file found
---
Changing user _usr-dba password
Changing user _usr-dba2 password
function should stop
Changing user _usr-dba3 password
function should stop
function should stop
function should stop
function should stop
function should stop
Disabling user DisableAccounts:{
Disable-LocalUser : User DisableAccounts:{ was not found.
At C:\Scripts\AWL-MS-AUTOMATION_AND_TOOLS\functions\AutoIndus-DisableAccount.ps1:25 char:13
+ Disable-LocalUser -Name $disable
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DisableAccounts:{:String) [Disable-LocalUser], UserNotFoundException
+ FullyQualifiedErrorId : UserNotFound,Microsoft.PowerShell.Commands.DisableLocalUserCommand
Disabling user _usr-dba
To help you understanding, my script read a file and do actions according to each line it is reading. It start acting when it encounter something like User{ and should stop when it encounter }, _usr-dba3 being out of the curvy brackets it should not be treated. This way all my other function use the same one file. (changing user password and diasabling user are two different functions/sourced scripts)
Like you can see return does not do its job, maybe I'm missing one point in the use of return but I don't get it right now.
To prematurely exit out of a function before you reach the end of it, use
return
it works like break to where it will stop execution but instead of stopping the whole thread it will return back to the line below where you called the function.
Also keep in mind if your function has an output set return will return it back, for example with the function below:
function Get-ReturnValue()
{
$returnValue = "this is my output"
return $returnValue
}
if you called it like this:
$receivedReturnValue = Get-ReturnValue
then the variable receivedReturnValue would be loaded with the output of the function.
I needed a fast solution so I changed my functions, now there is no return/continue/... but a value that turn true. It is initialized to false and the action on each yaml lines are done when the value is equal to false.
Edit: So finally the issue was I didn't used function correctly. Return only works if you return into another function. So I putted almost the entire sctipt into a function that calls the function AutoIndus-DeployUser. Now it works perfectly !
I'd like to use CasperJS to evaluate a variable equals a certain value.
I simplified my exemple as much as I could that way:
var testDate = "24/03/14";
casper.test.begin('TEST', 1, function suite(test) {
casper.start('http://www.google.com/', function() {
this.test.assertEval(function() {
return testDate == "24/03/14";
}, "testDate is 24/03/14" );
});
casper.run(function() {
this.test.done();
});
});
I don't know why it fails, here is what I get in my console:
Test file: tests.js
#TEST
FAIL testDate is 24/03/14
# type: assertEval
# file: tests.js:7
# code: }, "testDate is 24/03/14" );
# subject: null
# fn: undefined
# params: undefined
FAIL 1 test executed in 2.896s, 0 passed, 1 failed, 0 dubious, 0 skipped.
Details for the 1 failed test:
In tests.js:7
TEST
assertEval: testDate is 24/03/14
Any idea ?
UPDATE
I realised my simplified example was faulty, it didn't represent what I really needed.
Actually, what I want to achieve is to test if a variable from the current page DOM context equals a local variable.
As per manual Asserteval:
Asserts that a code evaluation in remote DOM strictly resolves to a boolean true:
your testdate variable is local to the casperjs script and is not accessible in the remote dom. You would have to inject it to the window like described here.
Ok found the answer myself.
To test if a variable from the current page DOM context equals a local variable, I realised I could use a simple assertEvalEquals():
test.assertEvalEquals(function() {
return variableFromPageDomContext;
}, localVariable);
Likewise, when testing if a variable from the current page DOM context matches a RegExp pattern, we have to use evaluate() to get the variable from the DOM as the first parameter of an assertMatch():
test.assertMatch(this.evaluate(function() {
return variableFromPageDomContext;
}), RegExpPattern);
Hope that can help.
As #Surreal answers its possible to use the assertEvalEquals() passing the function and the expected value.
However the original question wants to pass a variable from casperjs context to assertEval() function, you can simply do it as follows, passing to assertEval() three arguments: the function which receive the value, a message for the assert and the value:
var varPassToEval = 'someValue';
test.assertEval(
function(varFromCasperContext){
return varFromPageDomContext === varFromCasperContext;
},
'Assert Eval to test',
varPassToEval
);
With the above example probably is clear to use assertEvalEquals() however could be useful for more complex cases, for example imagine that you want to check if a text appears in a some <li> inside <ul> in DOM which it's dynamic and can change but you don't know at first where your text is... for this case you can use:
var somePartOfText = 'blue';
test.assertEval(
function(varFromCasperContext){
return document.getElementsByTagName("ul")[0].textContent.indexOf(varFromCasperContext) != -1;
},
'Assert Eval to test',
somePartOfText
);
Hope it helps,
If I have a very simple script that contains a function that just does the following:
function saySomething() {
Write-Output "Saying someting..."
}
If I call this function from the console the output is displayed. If I, however, do the following:
$something = saySomething
Then no output is displayed. Obviously my working example is much more complicated than this, but in short, how do I display the output within a function if that function is used to set a variable?
Try the following:
saySomething | Tee-Object -Variable something
This should work exactly as you want.
Is there a way to make a bash alias (or function) with its name coming from a variable?
For instance, is it possible to do something along these lines:
create_alias_with_name() {
alias $1="echo a custom alias"
}
Or something along these lines:
create_func_with_name() {
$1() {
"echo inside a function with a variable name"
}
}
In other words, I would prefer to have some kind of function "factory" that can register functions for me. Is this possible or beyond the capabilities of Bash?
Did you even try it? Your first example works fine.
You can make the second work by adding an eval:
create_func_with_name() {
eval "$1() {
echo inside a function with a variable name
}"
}
just in case, one may use a variable both as a part of the alias name and as a part of the alias command:
alias foo${var1}="bar${var2}"