I have a script that has some functions.
Can I run one of the function directly from command line?
Something like this?
myScript.sh func()
To invoke a function, simply use the function name as a command. To pass parameters to the function, add space separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3 etc.
To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.
A shell function may do neither, either or both. It is generally accepted that in shell scripts they are called functions. A function may return a value in one of four different ways: Change the state of a variable or variables.
Well, while the other answers are right - you can certainly do something else: if you have access to the bash script, you can modify it, and simply place at the end the special parameter "$@"
- which will expand to the arguments of the command line you specify, and since it's "alone" the shell will try to call them verbatim; and here you could specify the function name as the first argument. Example:
$ cat test.sh testA() { echo "TEST A $1"; } testB() { echo "TEST B $2"; } "$@" $ bash test.sh $ bash test.sh testA TEST A $ bash test.sh testA arg1 arg2 TEST A arg1 $ bash test.sh testB arg1 arg2 TEST B arg2
For polish, you can first verify that the command exists and is a function:
# Check if the function exists (bash specific) if declare -f "$1" > /dev/null then # call arguments verbatim "$@" else # Show a helpful error echo "'$1' is not a known function name" >&2 exit 1 fi
If the script only defines the functions and does nothing else, you can first execute the script within the context of the current shell using the source
or .
command and then simply call the function. See help source
for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With