Linux shell scripts have built-in support for functions, but those functions are not declared with return types as in other languages, so it’s not obvious how to return values from shell script functions. Return values are not supported by the language itself, but there are number of ways to generate a function result, similar to a return value. Three of these methods are to modify environment variables, generate an exit code, or generate prints.
Linux shell scripts do not have local variables; all variables are global. Because of this, a function can edit any variable and use it as a return value. The following example demonstrates this:
COOKIES_ARE_BAKED=false
bake_some_cookies() { if [ -x ~/my_oven ]; then if ~/my_oven bake cookies; then
# Set the environment variable to indicate baking succeeded. COOKIES_ARE_BAKED=true fi fi }
bake_some_cookies if [ $COOKIES_ARE_BAKED == true ]; then echo “Eating cookies” fi |
Functions in Linux shell scripts are run the same way as commands, and they can generate exit codes in the same way commands do. The exit code for a function is generated by using the return keyword. This keyword causes the function to stop running and generate an exit code. The following example demonstrates this:
bake_some_cookies() { if [ -x ~/my_oven ]; then if ~/my_oven bake cookies; then
# Generate a successful error code if baking succeeded. return 0 fi fi
# If we get here, baking failed. Generate an error code. return 1 }
if bake_some_cookies; then echo “Eating cookies” fi |
Just like commands, functions can also generate prints. And just like commands, those prints can be captured by using command substitution. The following example demonstrates this:
bake_some_cookies() { if [ -x ~/my_oven ]; then if ~/my_oven bake cookies; then
# Print something if baking succeeded echo “Eating cookies” fi fi }
# Using ‘$()’ syntax for command substitution. Backquotes can also be used. COOKIES_ARE_BAKED=$(bake_some_cookies) if [ “$COOKIES_ARE_BAKED” != “” ]; then echo “$COOKIES_ARE_BAKED” fi |