2

I have developed a script shell in OpenWrt as below, I noticed a strange behavior (the "return") as shown in my comments at the end of script. It returns 43 instead of 9003 and 45 instead of 9005, do you have any explanation for this behavior?

#!/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)
developer
  • 4,744
  • 7
  • 40
  • 55

3 Answers3

3

On most Unix systems, return values are interpreted as modulo 256. Since 9003 mod 256 is 43, and 9005 mod 256 equals 45, you get these return values, respectively.

1

H2CO3 already explained the reasoning behind the behaviour.

I can suggest a workaround: Print the numbers you need to be returned from the function to stdout, then capture it via command substitution.

i.e., change the places with returns from

return 9003

to

echo "9003"
return 0

and capture it with:

retVal=$(get_value aa 1)

So your code should look like this:

#!/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"

Just remember to redirect anything you don't want returned to retVal to /dev/stderr

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
1

The return value in POSIX compatible systems is only 1 byte = 8 bits = 255 possible values. Unless you find an odd system that supports more than that, you should pick a different set of values.

Se this question for more details on return code standards

Community
  • 1
  • 1
Jarmund
  • 3,003
  • 4
  • 22
  • 45