Shell函數參數

來源:互聯網
上載者:User

標籤:

在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來擷取參數的值,例如,$1表示第一個參數,$2表示第二個參數...

帶參數的函數樣本:

  1. #!/bin/bash
  2. funWithParam(){
  3. echo "The value of the first parameter is $1 !"
  4. echo "The value of the second parameter is $2 !"
  5. echo "The value of the tenth parameter is $10 !"
  6. echo "The value of the tenth parameter is ${10} !"
  7. echo "The value of the eleventh parameter is ${11} !"
  8. echo "The amount of the parameters is $# !" # 參數個數
  9. echo "The string of the parameters is $* !" # 傳遞給函數的所有參數
  10. }
  11. funWithParam 1 2 3 4 5 6 7 8 9 34 73

運行指令碼:

The value of the first parameter is 1 !The value of the second parameter is 2 !The value of the tenth parameter is 10 !The value of the tenth parameter is 34 !The value of the eleventh parameter is 73 !The amount of the parameters is 12 !The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"

注意,$10 不能擷取第十個參數,擷取第十個參數需要${10}。當n>=10時,需要使用${n}來擷取參數。

另外,還有幾個特殊變數用來處理參數,前面已經提到:

 

特殊變數 說明
$# 傳遞給函數的參數個數。
$* 顯示所有傳遞給函數的參數。
[email protected] 與$*相同,但是略有區別,請查看Shell特殊變數。
$? 函數的傳回值。

Shell函數參數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.