When we write functional scripts, we tend to place functions that are similar in operation or similar in parameters into the same shell script, which is easy to manage, easy to maintain, and clear. In this case, the usual approach is to define all the functions used in the shell script, and then invoke the specified corresponding function in the body code by reading the input command function arguments with a case statement. This makes it a powerful feature for a shell script to use.
The following is a simple example to illustrate. A calculator provides the functionality of the subtraction:
#!/bin/bashusage= "Usage: ' basename $ ' (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 this shell script above, we can achieve different purposes by passing in different parameter invocations.
[Email protected]]$./calculator Add 2 35[[email protected]]$./calculator Sub 2 3-1[[email protected]]$./calculator mul 2 36[[email protected]]$./calculator Div 2 30[[email protected]]$./calculator all 2 35-160[[email protected]]$./calcul Ator 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 arguments, that is, different function parameters? At this point we can read the parameters inside the function body, and then pass the corresponding arguments in the corresponding call statements after the case.
function double () { ans=$ ($ +) echo $ans}case $command in (Dou) double "$first" #you can also u Se "$" ;;
When we need to pass the command arguments intact to the calling function and ignore the command parameter, we can use the shift command once before the call. The shift command implements the left-hand side of the parameter so that the original first argument disappears.
If you want to pass the remaining parameters to the function intact, you can use the parameter $*; If the remaining arguments are made into a command string to the function, the parameter "$*" is used. The difference is whether to use quotation marks, when the quotation is actually only passed a parameter in the past, it is the current shell in the shift after the load of a combination of parameters, no quotation marks are the remaining parameters.
Shell script invokes the specified function through parameter passing