且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

shell函数的返回值不能大于255的问题

更新时间:2022-07-02 11:38:05

之前用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”,有个链接

Advanced Bash Shell Scripting Guide - Complex Functions and ...

跟进去,looking……………………………………………….
哇!发现了!
这个链接:http://tldp.org/LDP/abs/html/assortedtips.html#RVT
 
里面的代码真是金玉良言啊!O(∩_∩)O~
 
好了,这个链接来自于Advanced Bash-Scripting Guide.pdf这本书籍,Advanced 还算对得起我这个菜鸟写的程序,我的问题都要到Advanced里面去找啦,自己虚荣下下:)。
解决问题!准备看完UNIX+Shells+by+Example(4th)就看他啦!
Happy...





本文转自 xkdcc 51CTO博客,原文链接:http://blog.51cto.com/brantc/192823,如需转载请自行联系原作者