I have a script that has a bunch of different parameterized functions. Is it possible to call any of these functions from the command line and pass in the arguments instead of me having to hard code the function calls in the script?
F.Y.I: I do know how to execute a simple PHP script from the command line
doesn't quite call the function, remember script.php has around 5 different functions and I am looking to call only 1, is that possible
No, you cannot do that directly. You have a few options:
Put every function in a separate php file and call the php file
use the first argument passed to the php file as the function name, and write a few lines of code to select the correct function.
Update:
Here is a example of using the first passed parameter as a function call:
if(function_exists( $argv[1] ))
call_user_func_array($argv[1], $argv);
php script.php arg1 arg2
access them as $argv[1], $argv[2]...and so on, in your script.
Not 100% sure what you're asking, but the execution would be something like
php script.php arg1 arg2 arg3
You seem to already know that. The method for accessing those arguments within the script itself would be to use the variable $argv, so $argv[0] would be the script, $argv[1] would be "arg1", etc. If that doesn't work, then use $_SERVER['argv'].
As for options, you can parse them with getopt
You could make the command-line script use its first argument as the function to call, and subsequently the arguments to pass to it. The arguments will appear in the magic array variable $argv.
// Zero'th "argument" is just the name of your PHP script
$name_of_php_script = array_unshift($argv);
// Next argument will be your callback
$callback = array_unshift($argv);
// Remaining arguments are your parameters
call_user_func_array($callback, $argv);
Obviously, you may want to make things more complicated for security, or to pass in special values of some sort, but this does the basic logic you describe in the question.
You can write an option, then pass the function to that eg myscript.php -function my_function
then in your script call the function like
$argv[1]()
getopt() takes CLI parameters.
php /path/to/myscript.php -a foo -b bar -c baz
$arguments = getopt("a:b:c:");
print_r($arguments);
Array
(
[a] => foo
[b] => bar
[c] => baz
)
Make it a function $arguments[a](); to call foo(); you can pass in b also if you have a function arg.
Related
I have the following bash script but im unable to use my defined command "kctl" if i call it with "get pods". Do I maybe have to add a placeholder behind the command at the kctl() funtction or so?
#!/bin/bash
KCTL=$(which kubectl)
KUBECONFIG=$1
kctl() {
$KCTL --kubeconfig=$KUBECONFIG
}
kctl get pods
For some reason I always get back the kubectl help and not a list of pods at the default namespace.
Thanks in advance
Here ktcl is a function on its own, so it has its own parameters. When you use it in the end you pass additional parameters to it but then in the function you do nothing with them.
If your intention is to append the arguments to the command inside the function, you have to write it like this:
kctl() {
$KCTL --kubeconfig=$KUBECONFIG "$#"
}
Notice how the function doesn't see the arguments of the script, as they are shadowed by its own arguments.
I have a bash script which have some helper function inside a shared, common file lib.sh. However, some of these functions look like this:
function check_prs {
local labels
labels=$(hub pr show -h "${BRANCH:-}" -F '%L')
if [[ $PRLABELS == *"DOTHING"* ]]
then true
else false
fi
}
The problem is that the command substitution and labels variable assignment is done when the script is loaded (source lib.sh from my main script), regardless of whether the function is called (or when).
Is there a way to only make these command substitutions when the function is actually called? Or some other way to make it behave as everything else in the normal flow of the script?
I want to produce the same output as this:
bash utilities.bash "is_net_connected"
But I don't know how to pass "is_net_connected" if command and file is stored in a variable like this:
T=$(bash utilities.bash)
I've tried these but it doesn't seem to work. It's not picking up ${1} in utilities.bash.
$(T) "is_net_connected"
$(T "is_net_connected")
Not the best way to inport but I'm trying to avoid cluttering my main script with function blocks.
T=$(bash utilities.bash) doesn't save the command; it runs the command and saves its output. You want to define a function instead.
T () {
bash utilities.bash "$#"
}
# Or on one line,
# T () { bash utilities.bash "$#"; }
Now
T "is_net_connected"
will run bash utilities.bash with whatever arguments were passed to T. In a case like this, an alias would work the same: alias T='bash utilities.bash'. However, any changes to what T should do will probably require switching from an alias to a function anyway, so you may as well use the function to start. (Plus, you would have to explicitly enable alias expansion in your script.)
You might be tempted to use
T="bash utilities.bash"
$T is_net_connected
Don't be. Unquoted parameter expansions are bad practice that only work in select situations, and you will get bitten eventually if you try to use them with more complicated commands. Use a function; that's why the language supports them.
I know how to return an exit code, but I would like to return the result of an operation done in a shell script function, so I can eventually use it in another script or function.
Something like
var1=$(myfunction)
function2 var1
Where myfunction could be something like A+B=C
I looked into "return", but it will return a code, not a value.
I am looking into various sites that show how to write functions, but I don't see how you actually return values.
In C++ you would use return "variable name", but shell script won't allow this. It says that the variable do not exist (which is logical, it is a variable created in a function, so when the function is released, that memory space assigned to it is gone). Can't use global variables since the function may be in one script and the calling function that needs the return value, may be in a different one.
myfunction could be something like A+B=C
Just echo the result:
$ myfunction() { echo $(($1+$2)); }
The above myfunction adds two numbers and echoes the result.
The return value can then be captured just as you had it:
$ var=$(myfunction 12 5)
$ echo $var
17
The construct var=$(myfunction) captures the standard out from myfunction and saves it in var. Thus, when you want to return something from myfunction, just send it to standard, like we did with echo in the example above.
In cases where you want the return value to be carefully formatted, you should consider using printf in place of echo.
More: How to return multiple values
Let's define a function that produces two outputs:
$ f() { echo "output1" ; echo "output2" ; }
$ f
output1
output2
If you want to get those values back separately, the most reliable method is to use bash's arrays:
$ a=($(f))
The above executes f, via $(f) and saves the results in an array called a. We can see what is in a by using declare -p:
$ declare -p a
declare -a a='([0]="output1" [1]="output2")'
I use the same sorta thing for returning values from other scripts to my main script like the title suggests.
At the end of the 2nd script, I echo the variable I want to return to the main script:
#!/bin/bash
# This is the Second Script.
# Store the variables passed from the main script:
VAR1_FROM_MAIN_SCRIPT=$1
VAR2_FROM_MAIN_SCRIPT=$2
# Add the 2 variables and store as another variable to return:
RETURN_THIS=$(($VAR1_FROM_MAIN_SCRIPT + VAR2_FROM_MAIN_SCRIPT))
# This is the variable you are sending back to the main script:
echo "$RETURN_THIS" #<---- This won't print to screen!!!
Then in the main script I pass in a couple variables to, and execute, the 2nd script like this:
#!/bin/bash
# This is the Main Script.
PASS_VAR1_TO_SCRIPT=1
PASS_VAR2_TO_SCRIPT=2
# Call the second script and store it's results in this variable:
RETURN_VARIABLE=$(./secondScriptName "$PASS_VAR1_TO_SCRIPT" "$PASS_VAR2_TO_SCRIPT")
# Display the returned variable from the second script:
echo $RETURN_VARIABLE #<---- Will display 3
The reason the echo in the second script won't print to screen, is because it's running that second script in a subshell from the RETURN_VARIABLE... I know my explanation of the subshell sucks, but that's besides the point...
Also, I know you can source the other script, but this might help others.
In shell scripting you don't return a value but just echo (print) it and caller would capture the output of your script/function to grab the returned value.
Example:
dateval=$(date)
echo $dateval
Wed Apr 23 18:35:45 EDT 2014
Instead of date you can place your function or your shell script.
Suppose I have a function "func" which gets two arguments "a" and "b" and returns something.
For some reason I can't manage echo what I get from the function.
This is what I tried:
value=$(func $a $b)
echo $value
Since you didn't show your function definition, this is only a guess, but I'm pretty confident it's a good one.
You need to understand that a function in shell fits into the language as if it was a command, i.e. a separate program, and the return keyword is analogous to exit. You can only return small integers, and the caller sees them in $?, just like the exit value of any other command.
Functions can also output a result to stdout by using echo (or any other command that prints to stdout), and then the result can be caputred with $(func args ...)
So you probably just need to change return to echo in your function.