和其他腳本語言一樣,bash同樣支持函數。我們可創建特定的函數,也可以創建能夠接受參數的函數。需要的時候直接調用就可以了。
1.定義函數
function fname() { statements; } 或者: fname() { statements; }
只需要使用函數名,就可以調用某個函數
例如:
[root@gitlab script]# cat function_test.sh #!/bin/bash function fname() { echo "This is test function"; #;也可不用 } for i in {1..5} do fname; #調用函數 ;也可不用 done [root@gitlab script]# ./function_test.sh This is test function This is test function This is test function This is test function This is test function
2.函數傳參
[root@gitlab script]# cat function_test.sh #!/bin/bash function fname() { echo $1 $2 #打印參數 echo "$@" #以列表的方式一次性打印所有參數 echo "$*" #類似於$@,但單數被作為單個實體 } fname hello world #傳參 echo "##########################" fname 1 2 [root@gitlab script]# ./function_test.sh hello world hello world hello world ########################## 1 2 1 2 1 2