Bash (Scripting) - Returning values from a function

by
Jeremy Canfield |
Updated: August 10 2023
| Bash (Scripting) articles
This assumes you are familiar with Bash Functions. If not, check out my article Getting Started with functions.
Returning values from a function is Bash is rough. Whenever possible, I would instead go with some other scripting language, such as Python or Perl. But, if you must use Bash, here is an example of how you can have a function that returns a value.
#!/bin/bash
function request {
echo hello
}
response=$(request)
echo "response = $response"
In this example, "hello" should be returned, like this.
~]$ bash example.sh
response = hello
As a much more practical example, here is a function that should return the return code of a command.
#!/bin/bash
function ps_command_return_code {
stdout=$(ps -ef | grep foo | grep -v " grep ")
rc=$?
echo $rc
}
return_code=$(ps_command_return_code)
echo "return_code = $return_code"
In this example, 0 or 1 should be returned.
~]$ bash example.sh
return_code = 1
Did you find this article helpful?
If so, consider buying me a coffee over at