Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() 
like image 884
AAaa Avatar asked Jan 11 '12 11:01

AAaa


People also ask

How do you execute a function in a shell script?

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.

How do you call a function inside a bash script?

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.

Can we use function in shell script?

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.


2 Answers

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 
like image 53
sdaau Avatar answered Nov 06 '22 05:11

sdaau


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.

like image 22
Sven Marnach Avatar answered Nov 06 '22 03:11

Sven Marnach