Returning a Function Result

Learn how we can return some value from a function.

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:

  1. Bash meets the function name in the command.

  2. The interpreter goes to the function body and executes it starting from the first command.

  3. 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.

  4. 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:

  1. The command substitution.

  2. A global variable.

  3. 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 1200+ tech skills courses.