7.3.6.3. Returning values from functions¶
Sometimes it is usefull to write a function that returns some value. Bash
functions don’t allow us to do this. There is a return
keyword, but this
sets the exit value of the function, just as the exit value of a script, as
described here:
alert () {
echo "An error occured!"
echo $1
return 2
}
When this function is run, the exit code will be 2:
% alert "the file does not exist."
An error occured!
the file does not exist.
% echo $?
2
%
This can be used in the same way as the exit code from a shell script, for example in an if statement.
The get a real value out of a function, command substition can be used. The function has to print the value to return to stdout, where it can be captured by the command substition construction:
# define the sqrt function to calculate the square root of a number
sqrt () {
echo "sqrt($1)" | bc -l # echo puts the result on stdout
}
sqrt2=$(sqrt 2) # capture the output of "sqrt 2" in the variable sqrt2
A somewhat larger example:
hypothenusa () {
cat <<EOF | bc -l
h_square=$1*$1 + $2*$2
h=sqrt(h_square)
print h # need to use print to return the value
EOF
}
hyp=$(hypothenusa 3 4) # sets hyp to 5