Return values from Bash shell functions.
They say Bash shell functions cannot return values, but only exit codes.
At Nerdstock, we know better.
A simple example:
#!/usr/bin/env bash
# First, create your function; have it echo() or printf() the result.
function sayHello() {
echo "Hello"
return 0
}
# Then, execute your function in a subshell,
# as you would with any other command.
greeting=$(sayHello)
echo "${greeting} world!"
# Output:
# Hello world!
Another example:
#!/usr/bin/env bash
# First, create your function; have it echo() or printf() the result.
function add5() {
input=$@
echo $((${input} + 5))
return 0
}
# Then, execute your function in a subshell,
# as you would with any other command.
for ((i=0; i<5; i++)); do
echo "${i} + 5 = `add5 ${i}`"
done
# Output:
# 0 + 5 = 5
# 1 + 5 = 6
# 2 + 5 = 7
# 3 + 5 = 8
# 4 + 5 = 9
It's that simple…
| Responses are welcomed: rob[at]nerdstock.org |
![]() http://creativecommons.org/licenses/by-nc-sa/3.0/nl/deed.en |







