Reputation: 749
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?
Upvotes: 3
Views: 5609
Reputation: 14768
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:
add arg1 arg2
If by command line, you must load the contents of your .sh
file -- your function definitions --, so that you may call them from your shell. In this one case, you file should look like:
#! /bin/bash
add () {
a=$1
b=$2
c=$(expr $a + $b)
echo $c
}
And would use the function in your shell by doing the following:
source script.sh
add 100 1000
If in your script.sh file, you use:
./script.sh arg1 arg2
And the contents of the script file would be:
#! /bin/bash
add () {
a=$1
b=$2
c=$(expr $a + $b)
echo $c
}
add $1 $2
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 cmd
or $(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:
#! /bin/bash
add () {
a=$1
b=$2
c=$(expr $a + $b)
echo $c
}
add $1 $2
sub() {
a=$1
b=$2
c=$(expr $a - $b)
echo $c
}
sub $3 $4
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:
add () {
let i=$1 + $2
}
And the for loop being performed as:
for (( i = 0; i < 10; i++ )); do
echo $i
add i 5
echo $i
done
The output is:
0
5
6
11
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.
Upvotes: 7