eval
除了return,还有其他一些buildin的关键字,比如eval,local。
默认在当前脚本定义的变量都是全局变量,在方法中则可以通过local来定义局部变量,这样可以避免全局变量污染.
同时结合eval赋值语句,来实现变量的修改
returnString(){
local __result=$2
eval $__result=$1
}
returnString $1 result
echo "result=$result"
同样我们也得到了希望的结果
aven-mac-pro-2:avenwu.github.io aven$ ./testReturn hello result=hello aven-mac-pro-2:avenwu.github.io aven$ ./testReturn 500 result=500 aven-mac-pro-2:avenwu.github.io aven$ ./testReturn 12 result=12
echo
最后在介绍一种方法,通过echo输出,结合command substitution。
这个command substitution也没有找到比较合适的翻译,姑且按字面意思翻译命令替换。
如果你的方法内部只有一处echo输出,那么也可以利用她来进行值得返回,不过这个就有点局限性,一定要确保方法内只有一次输出,否则就会出现赋值内容过多。
returnString(){
local __result=$1
echo $__result
}
# 或者 result=`returnString $1`
result=$(returnString $1)
echo "result=$result"
同样可以得到预期结果
aven-mac-pro-2:avenwu.github.io aven$ ./testReturn hello result=hello aven-mac-pro-2:avenwu.github.io aven$ ./testReturn 500 result=500 aven-mac-pro-2:avenwu.github.io aven$ ./testReturn 12 result=12
越界问题
现在我们已经有几种办法可以返回字符串了,那么return返回数字有时候正确,有时候又不正确是为什么呢?
我们知道return原本就是用于返回执行状态的,比如0,1.那么我们在返回500的时候,实际上是数据溢出了。
根据测试,我们推断shell的内置return承接返回值用的是一个字节的大小,也就是8位,最多可以输出无符号0-255的整形,范围之外的数据全部溢出显示。因此在使用return的时候,务必留意数值大小。
小结
通过shell命令可以很方便的写出一些小脚本,但是如果遇到逻辑复杂,建议通过其他更合适的预览来实现,比如Python,Golang之类。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。










