Bash Function Return Values
A function return value is a status number from 0 to 255. It reports success or failure, not a computed result.
return sets a success or failure status
The function returns 0 when the file exists and 1 when it does not. Each echo shows the status left by the call just before it.
check_file() {
if [ -f "$1" ]; then
return 0
else
return 1
fi
}
printf 'data\n' > note.txt
check_file note.txt
echo "note: $?"
check_file missing.txt
echo "missing: $?"Echo the result, return the status
The function prints its sum, and the caller captures that printout. The status stays 0, separate from the captured number.
add() {
echo $(( $1 + $2 ))
}
total=$(add 19 23)
echo "total: $total"
echo "status: $?"A return value above 255 wraps around
The function returns 300, which is past the limit of 255. The status wraps by 256, so the caller sees 44.
give_back() {
return 300
}
give_back
echo "status: $?"Test the status right after the call
Each call is followed at once by a test of $?. No other command runs in between, so nothing overwrites the status.
is_big() {
if [ "$1" -gt 100 ]; then
return 0
else
return 1
fi
}
is_big 150
if [ "$?" -eq 0 ]; then
echo "150 is big"
fi
is_big 40
if [ "$?" -eq 0 ]; then
echo "40 is big"
else
echo "40 is not big"
fiExample
describe() {
if [ "$1" -gt 100 ]; then
echo "too big"
return 2
fi
echo "value: $1"
return 0
}
out=$(describe 42)
echo "$out"
describe 42
echo "status: $?"
describe 150
echo "status: $?"Key points
- return: ends a function at once and sets its exit status.
- return 0: the usual signal for success.
- Nonzero return: the usual signal for failure, with each number free to mean one kind of failure.
- Echo a result: print a computed value so the caller can capture it with $().
- $?: holds the exit status of the last command, so read it right after the call.
- Return wrap: a return value above 255 wraps modulo 256, so 300 becomes 44.
In this example, describe prints a message and returns a status for each value. A value over 100 prints too big and returns 2. Any other value prints the value itself and returns 0. The first call captures the printed value into out, while the later calls show the status left behind.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A function runs return 300. What does $? hold after the call?