Returning a Function Result
Learn how we can return some value from a function.
We'll cover the following
return
Most procedural languages have a reserved word for returning the function result. In most languages, this is called **return**
. Bash also has a built-in with the same name, however, it has another purpose. The return
command in Bash does not return a value. Instead, it provides a function exit status to the caller. This status is an integer between 0 and 255.
The complete algorithm of calling and executing the function looks this way:
-
Bash meets the function name in the command.
-
The interpreter goes to the function body and executes it starting from the first command.
-
If Bash meets the
return
command in the function body, it stops executing it. The interpreter jumps to the place where the function was called. The special parameter$?
keeps an exit status of the function. -
If there is no
return
command in the function body, Bash executes it until the last command. Then, the interpreter jumps to the place where the function was called.
In a typical procedural language, the return
command returns a variable of any type from a function. It can be a number, string, or array. We need other mechanisms for doing that in Bash. There are three options:
-
The command substitution.
-
A global variable.
-
The caller specifies a global variable.
Let’s consider these approaches with examples.
We wrote the code_to_error
and print_error
functions to print error messages. The file print-command-substitution.sh
has their declarations:
Click on the Run button and run the commands in the terminal below.
Run
cat debug.log
to read the log file.
Get hands-on with 1400+ tech skills courses.