天天看點

shell函數的傳回值不能大于255的問題

之前用Korn Shell寫了一個列出指定目錄下有多少日志檔案的小腳本,用得那個得心應手啊! 

忽然今天,我發現它出錯了!顯示有多少個日志值時錯了!

我暈哦!這個腳本我測了很多次了哦,用了很多次了哦,沒有錯的嘛!靠!

我反複檢查反複檢查,不行,還是有問題,明明有260個日志,怎麼隻報4? 

我把使用find的腳本單獨執行,對的啊,260!怎麼用函數get_count一調用後,傳回的值列印就是4呢? 

相當奇了怪了!

隻有看書了。

打開UNIX+Shells+by+Example(4th)跳到Chapter 11. The Interactive Korn Shell,看11.12 function,發現沒有講什麼;然後跳到Chapter 12. Programming the Korn Shell,12.8 function,有講!裡面有個Example是使用了傳回值的,我仔細看了看,和我的沒有什麼差别啊! 

就這樣一次,兩次,我再浏覽時,忽然發現:

The return value of a function is really just the value of the exit status of the last command in the script unless a specific return command is used. If a value is assigned to the return command, that value is stored in the ? variable. It can hold an integer value between 0 and 255. Because the return command is limited to returning only integer values, you can use command substitution to return the output of a function and assign the output to a variable, just as you would if getting the output of a UNIX command.

媽喲!怎麼原來就沒有發現呢!這可怎麼辦啊?我隻有google了,search “how to return a integer bigger than 255 shell”,有個連結

<a href="http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=2&amp;url=http%3A%2F%2Fwww.linuxtopia.org%2Fonline_books%2Fadvanced_bash_.ing_guide%2Fcomplexfunct.html&amp;ei=Ww-JStbaKoGJkQWx_OyeBw&amp;usg=AFQjCNFX2ThQ1EaXtwUZ-heMKDdGUA49TA&amp;sig2=Gl55aCQjTK_8_Wv5lbFDgA">Advanced Bash Shell Scripting Guide - Complex Functions and <b>...</b></a>

跟進去,looking……………………………………………….

哇!發現了!

裡面的代碼真是金玉良言啊!O(∩_∩)O~

好了,這個連結來自于Advanced Bash-Scripting Guide.pdf這本書籍,Advanced 還算對得起我這個菜鳥寫的程式,我的問題都要到Advanced裡面去找啦,自己虛榮下下:)。

解決問題!準備看完UNIX+Shells+by+Example(4th)就看他啦!

Happy...

本文轉自 xkdcc 51CTO部落格,原文連結:http://blog.51cto.com/brantc/192823,如需轉載請自行聯系原作者