Say I have the following two Bash scripts:
Version #1:
#!/bin/bash
function bar
{
if true; then
echo "error" >&2
exit 1
fi
echo "bar"
}
function foo
{
local val=`bar`
echo $?
echo "val: $val"
}
foo
With version #2 second having a slightly different foo:
function foo
{
val=`bar` #note no 'local'
echo $?
echo "val: $val"
}
Version #1 gives me the following output:
error
0
val:
Whilst version #2 gives me this:
error
1
val:
The inclusion of local in #2 appears to hide the return value of bar.
Am I correct in thinking this is because local is itself a function, and is returning 0? And if so, is there a way around this and make val a local variable, but still test the return value of bar?
Yes, you are reading the return value of
localwhich was successful. The fix is to separate the variable declaration from its definition like so:Output