Is it possible to call a function (defined in a shell script) from Unix console? I have a function like
add ()
{
a=$1
b=$2
c=`expr $a + $b`
}
This is defined in the script "my_script.sh". How to call this function from command prompt?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To use arguments you don’t apply the redirection operator
<, which redirects the file given right after the<to the standard input of your program. You need to make a call of your function in your script, in order to use the args$..., or you can simply load the function in your shell, and use it.In both cases, the call of your function is to be performed like this:
If by command line, you must load the contents of your
.shfile — your function definitions –, so that you may call them from your shell. In this one case, you file should look like:And would use the function in your shell by doing the following:
If in your script.sh file, you use:
And the contents of the script file would be:
Obs: your syntax was not valid in the function definition: you must embrace an expression in order to assign the result of it’s evaluation; the syntax for evaluating an expression may be either
cmdor $(cmd), with the difference that the first approach allows no nesting calls.If you have more than one function being defined, you can either set the args for each function call, or simply define your functions, and load them up to your shell with “source script.sh”.
Since you’ve loaded the functions, you need to call them as well as if they’ve been defined one by one. The args inside the function correspond to the classic “argv[]” parameters in C, they’re unique to the function call.
For example, if you wanted to define an add and a sub function, you’d have:
Or whatever argument numbers may fits your application.
Notice, though, that you might lose track of the “semantic” of the vars: this can be caused by the dynamic scope of bash scripting, which shadows your variable definitions each time a call is performed.
A straightforward example of this is a for loop. Consider the add function defined as follows:
And the for loop being performed as:
The output is:
since the variable “i” has been modified, during the for loop, not only by the “i++”, but by the function “add”, that has “i” being used in its scope.