Returning a Function Result
Explore how to manage function results in Bash programming by understanding the use of return for exit statuses, and the techniques to return values such as command substitution, global variables, and caller-specified variables. This lesson helps you avoid naming conflicts and write clearer functions for automation.
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
returncommand 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
returncommand 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: