why is that when grep -c
returns 0
, script fails with '-1' exit code. This happens only when set -o errexit
is set.
cat <<'EOT' > /tmp/foo.sh
#!/usr/bin/env bash
function bash_traceback() {
local lasterr="$?"
set +o xtrace
local code="-1"
local bash_command=${BASH_COMMAND}
echo "Error in ${BASH_SOURCE[1]}:${BASH_LINENO[0]} ('$bash_command' exited with status $lasterr)"
if [ ${#FUNCNAME[@]} -gt 2 ]; then
# Print out the stack trace described by $function_stack
echo "Traceback of ${BASH_SOURCE[1]} (most recent call last):"
for ((i=0; i < ${#FUNCNAME[@]} - 1; i++)); do
local funcname="${FUNCNAME[$i]}"
[ "$i" -eq "0" ] && funcname=$bash_command
echo -e " $i: ${BASH_SOURCE[$i+1]}:${BASH_LINENO[$i]}\t$funcname"
done
fi
echo "Exiting with status ${code}"
exit "${code}"
}
test_redirecting_of_stdout_stderr() {
# Exit program when error found
set -o errexit
# Exit program when undefined variable is being used
set -o nounset
local up_count
up_count=$(ls | grep -c NOTHING_MATCHED)
echo "up_count: $up_count"
}
# provide an error handler whenever a command exits nonzero
trap 'bash_traceback' ERR
set -o errtrace
test_redirecting_of_stdout_stderr
EOT
bash /tmp/foo.sh
debian:~/my-mediawiki-docker$ bash /tmp/foo.sh
Error in /tmp/foo.sh:31 ('up_count=$(ls | grep -c NOTHING_MATCHED)' exited with status 255)
Traceback of /tmp/foo.sh (most recent call last):
0: /tmp/foo.sh:31 up_count=$(ls | grep -c NOTHING_MATCHED)
1: /tmp/foo.sh:40 test_redirecting_of_stdout_stderr
Exiting with status -1
debian:~/my-mediawiki-docker$
grep
reports "failure" if it fails to find any matching lines. Here's man grep
:
EXIT STATUS
The exit status is 0 if selected lines are found, and 1 if not found.
If you want to allow a command to exit with non-zero without terminating the script during errexit
, use || true
:
up_count=$(ls | grep -c NOTHING_MATCHED) || true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With