1.12 Functions and Parameters
- Like other scripting languages, Bash also supports functions and can pass parameters.
1.12.1 function definition and parameter transfer
#!/bin/bash function fname () #也可以用fname () instead of {echo $1 , $2 ; #访问参数1和参数2 echo "[email protected] " ; #以列表的方式一次性打印所有参数 echo "$*" ; #类似于 [email protected], but the parameter is used as a single entity return 0 ; #返回值 } fname $1 $2 #执 row functions and pass parameters
- $1 is the first parameter;$2 is the second parameter;$n is the nth parameter;$@ is expanded to "$1 ""$2 ""$3 ";$* is expanded to " 1c 2c$3 ", where C is the first character of the IFS.
1.12.2 recursive function
- In bash, functions also support recursive functions.
F(){ echo$1; F hello; 1;}
1.12.3 Read command return value
- The return value is called the eject state , which can be used to analyze whether the command executes successfully or not. If the command exits successfully, the exit status is 0, otherwise it is not 0.
#!/bin/bashCMD="echo test" #CMD为要执行的命令$CMD #执行命令if-eq0 ] #$?为退出状态then echo"$CMD executed successfully"else echo"$CMD executed unsuccessfully"fi
1.12.4 passing parameters to a command
- Commands in bash usually have multiple parameters, and the parameters of the command can be passed in different formats. Assuming that-p,-v is an available option, K n is another acceptable parameter, and you can accept a file name as a parameter, then several ways are equivalent:
-p-v-k1-pv-k1-vpk1-file-pvk1 #k N应该紧邻
1.12.5 Reference
- Linxu Shell Script Raiders
Linux Shell Script Raiders (1.12)