shell 函數(特定的函數和腳本內傳參)


和其他腳本語言一樣,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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM