Shell函數傳回值、刪除函數、在終端調用函數

來源:互聯網
上載者:User

標籤:

Shell 也支援函數。Shell 函數必須先定義後使用。

Shell 函數的定義格式如下:

function_name () {    list of commands    [ return value ]}

如果你願意,也可以在函數名前加上關鍵字 function:

function function_name () {    list of commands    [ return value ]}

函數傳回值,可以顯式增加return語句;如果不加,會將最後一條命令運行結果作為傳回值。

Shell 函數傳回值只能是整數,一般用來表示函數執行成功與否,0表示成功,其他值表示失敗。如果 return 其他資料,比如一個字串,往往會得到錯誤提示:“numeric argument required”。

如果一定要讓函數返回字串,那麼可以先定義一個變數,用來接收函數的計算結果,指令碼在需要的時候訪問這個變數來獲得函數傳回值。

先來看一個例子:

  1. #!/bin/bash
  2. # Define your function here
  3. Hello () {
  4. echo "Url is http://see.xidian.edu.cn/cpp/shell/"
  5. }
  6. # Invoke your function
  7. Hello

運行結果:

$./test.shHello World$

調用函數只需要給出函數名,不需要加括弧。

再來看一個帶有return語句的函數:

  1. #!/bin/bash
  2. funWithReturn(){
  3. echo "The function is to get the sum of two numbers..."
  4. echo -n "Input first number: "
  5. read aNum
  6. echo -n "Input another number: "
  7. read anotherNum
  8. echo "The two numbers are $aNum and $anotherNum !"
  9. return $(($aNum+$anotherNum))
  10. }
  11. funWithReturn
  12. # Capture value returnd by last command
  13. ret=$?
  14. echo "The sum of two numbers is $ret !"

運行結果:

The function is to get the sum of two numbers...Input first number: 25Input another number: 50The two numbers are 25 and 50 !The sum of two numbers is 75 !

函數傳回值在調用該函數後通過 $? 來獲得。

再來看一個函數嵌套的例子:

  1. #!/bin/bash
  2. # Calling one function from another
  3. number_one () {
  4. echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
  5. number_two
  6. }
  7. number_two () {
  8. echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
  9. }
  10. number_one

運行結果:

Url_1 is http://see.xidian.edu.cn/cpp/shell/Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/

像刪除變數一樣,刪除函數也可以使用 unset 命令,不過要加上 .f 選項,如下所示:

  1. $unset .f function_name

如果你希望直接從終端調用函數,可以將函數定義在主目錄下的 .profile 檔案,這樣每次登入後,在命令提示字元後面輸入函數名字就可以立即調用。

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.