How can I run a function from a script in command line? How can I run a function from a script in command line? linux linux

How can I run a function from a script in command line?


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.shtestA() {  echo "TEST A $1";}testB() {  echo "TEST B $2";}"$@"$ bash test.sh$ bash test.sh testATEST A $ bash test.sh testA arg1 arg2TEST A arg1$ bash test.sh testB arg1 arg2TEST 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/nullthen  # call arguments verbatim  "$@"else  # Show a helpful error  echo "'$1' is not a known function name" >&2  exit 1fi


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.


The following command first registers the function in the context, then calls it:

. ./myScript.sh && function_name