Why ?
It is very important to write code with function, even if sometimes I'm to lazy to do it, This Is Important !
Important, ok, but by essence, bash is built to return only interger return code between 0 and 255.
This is a great limitation because if we want to return, something like... True :troll:
or everything else than integer value, the return statement doesn't return anything.
We can try:
#!/bin/bash
function fun_a(){
i=0
for j in a b c; do
((i++))
done
return $i
}
fun_a
echo $?
function fun_b(){
msg="Hello, $1 !"
return $msg
}
fun_a
fun_b "operator"
This will produce this result:
3
i: line 16: return: Hello,: numeric argument required
How ?
Like we see, the return statement is not agree with that !
Instead it is possible to use the command echo and simply call the function
with the command substitution $() (it parent's is ` `) and store it into a variable.
#!/bin/bash
function fun_b(){
msg="Hello, $1 !"
echo $msg
}
res_b=$(fun_b "operator")
echo $res_b
For this result:
Hello, operator !