從bash函數中返回任意值

來源:互聯網
上載者:User

從bash函數中返回任意值 Bash函數,不同於其他程式設計語言的函數,它更像一個子程式,即其傳回值,只能是一個數字,以0表示成功,非0表示失敗。如果,在bash函數中想返回除了數字之外的值,有三種方法:  www.2cto.com   1.假設我們想返回一個字串,最簡單的方法是:Shell代碼  function myfunc()  {      myresult='the value'  }  myfunc  echo $myresult   通過一個全域變數myresult,來儲存傳回值。使用全域變數,其缺點也是不言而喻的。   www.2cto.com  2.第二種方法:Shell代碼  function myfunc()  {      local  myresult='some value'      echo "$myresult"  }     result=$(myfunc)   # or result=`myfunc`  echo $result   將一個shell函數作為一個子程式調用,將傳回值寫到子程式的標準輸出,來達到返回任一字元串的目的。  3.第三種方法:Shell代碼  function myfunc()  {      local  __resultvar=$1      local  myresult='some value'      eval $__resultvar="'$myresult'"  }     myfunc result  echo $result   這種方法,類似於C++中的通過引用返回函數值的做法。  www.2cto.com  另外,還可以結合後兩種方法:Shell代碼  function myfunc()  {      local  __resultvar=$1      local  myresult='some value'      if [[ "$__resultvar" ]]; then          eval $__resultvar="'$myresult'"      else          echo "$myresult"      fi  }     myfunc result  echo $result  result2=$(myfunc)  echo $result2   這樣,獲得了最大的靈活。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.