2012-11-14 145 views
2

我在OpenWrt中开发了一个脚本shell,如下所示,我注意到脚本结尾处的注释中显示了一个奇怪的行为(“返回”)。它返回43而不是9003和45而不是9005,你对这种行为有任何解释吗?在shell脚本中返回命令

#!/bin/sh 

get_value() { 
case "$1" in 
    aa) 
    if [ "$2" = "1" ]; then 
     return 9003 
    fi 
# function fn1 to execute 
    fn1 
    return 0 
    ;; 
    bb) 
    if [ "$2" = "1" ]; then 
     return 9003 
    fi 
# function fn2 to execute 
    fn2 
    return 0 
    ;; 
    cc) 
    if [ "$2" = "1" ]; then 
     return 9003 
    fi 
# function fn3 to execute 
    fn3 
    return 0 
    ;; 
esac 
return 9005 
} 
# when a call get_value 
get_value aa 0 
echo $? 
# result 0 
get_value aa 1 
echo $? 
# result 43 (not 9003) 
get_value dd 1 
echo $? 
# result 45 (not 9005) 

回答

3

在大多数Unix系统中,返回值被解释为模256自9003 MOD 256是43,而9005 MOD 256等于45,你分别得到这些返回值。

1

H2CO3已经解释了行为背后的推理。

我可以建议一种解决方法:将需要从函数返回的数字打印到标准输出,然后通过命令替换将其捕获。

即从

return 9003 

改变与回报的地方

echo "9003" 
return 0 

,并捕捉到它:

retVal=$(get_value aa 1) 

所以,你的代码应该是这样的:

#!/bin/sh 

get_value() { 
case "$1" in 
    aa) 
    if [ "$2" = "1" ]; then 
     echo "9003" 
     return 0 
    fi 
# function fn1 to execute 
    fn1 
    echo "0" 
    return 0 
    ;; 
    bb) 
    if [ "$2" = "1" ]; then 
     echo "9003" 
     return 0 
    fi 
# function fn2 to execute 
    fn2 
    echo "0" 
    return 0 
    ;; 
    cc) 
    if [ "$2" = "1" ]; then 
     echo "9003" 
     return 0 
    fi 
# function fn3 to execute 
    fn3 
    echo "0" 
    return 0 
    ;; 
esac 
echo "9005" 
return 0 
} 

retVal=$(get_value aa 0) 
echo "$retVal" 

retVal=$(get_value aa 1) 
echo "$retVal" 

retVal=$(get_value dd 1) 
echo "$retVal" 

只要记住任何你不想回到retVal的重定向到/dev/stderr

1

在POSIX兼容的系统返回的值只有1个字节= 8位= 255倍可能的值。除非你发现一个支持更多的奇怪系统,否则你应该选择一组不同的值。

Se this问题有关返回代码标准的更多详细信息