The Shell script calls a specified function through passing parameters.
When writing some functional scripts, we usually put functions with similar operations or similar parameters in the same shell script, which is convenient to manage, easy to maintain, and clear. In this case, the common method is to define all the functions used in the shell script, and then read the input command function parameters in the body code using the case statement to call the specified function. In this way, a powerful shell script is used.
The following is a simple example. A calculator provides the addition, subtraction, multiplication, and Division functions:
#!/bin/bashusage="Usage: `basename $0` (add|sub|mul|div|all) parameter1 parameter2"command=$1first=$2second=$3function add() { ans=$(($first + $second)) echo $ans}function sub() { ans=$(($first - $second)) echo $ans}function mul() { ans=$(($first * $second)) echo $ans}function div() { ans=$(($first / $second)) echo $ans}case $command in (add) add ;; (sub) sub ;; (mul) mul ;; (div) div ;; (all) add sub mul div ;; (*) echo "Error command" echo "$usage" ;;esac
In the preceding shell script, we can call different parameters for different purposes.
[hdfs@cdhonf]$ ./calculator add 2 35[hdfs@cdhonf]$ ./calculator sub 2 3-1[hdfs@cdhonf]$ ./calculator mul 2 36[hdfs@cdhonf]$ ./calculator div 2 30[hdfs@cdhonf]$ ./calculator all 2 35-160[hdfs@cdhonf]$ ./calculator a 2 3Error commandUsage: calculator (add|sub|mul|div|all) parameter1 parameter2
What if we don't want each function to use the same number of parameters, that is, when different function parameters are different? At this time, we can read the parameters inside the function body, and then input the corresponding parameters in the corresponding call statement after case.
function double() { ans=$(($1 + $1)) echo $ans}case $command in (dou) double "$first" #you can also use "$2" ;;
When we need to pass the parameters after command to the call function, but ignore the command parameter, we can use the shift command before calling. Shift command to shift the parameter to the left, so that the original first parameter disappears.
If you want to pass the remaining parameters to the function intact, you can use the parameter $ *. If you want to send the remaining parameters to the function as a command string, you can use the parameter "$ *". The difference is whether to use quotation marks. When there are quotation marks, only one parameter is actually passed in. It is a combination of parameters loaded after shift in the current shell. If there is no quotation marks, it is the remaining parameters.