sh: "local" assignment from command loses exit status
Eric van Gyzen
eric at vangyzen.net
Thu Nov 6 17:20:32 UTC 2014
Jilles and -current:
In sh, if I use a single statement to declare a local variable and
assign the output of a command to it, the exit status of that command is
lost. For example:
should_return_false() {
local var1=`false`
}
The function should return non-zero, but it returns zero. This becomes
especially apparent when using the errexit option (-e flag), since the
shell should exit, but it does not.
Splitting the declaration and assignment into two lines works around the
[suspected] bug.
A more complete example follows.
Cheers,
Eric
#!/bin/sh
returns_false() {
var1=`false`
}
if returns_false; then
echo 1:FAIL
else
echo 1:PASS
fi
should_return_false() {
local var1=`false`
}
if should_return_false; then
echo 2:FAIL
else
echo 2:PASS
fi
workaround_returns_false() {
local var1
var1=`false`
}
if workaround_returns_false; then
echo 3:FAIL
else
echo 3:PASS
fi
set -o errexit
trap 'echo 4:PASS' EXIT
should_return_false
trap '' EXIT
echo 4:FAIL # because the shell should have exited
More information about the freebsd-current
mailing list