shellcheck
shellcheck copied to clipboard
Exceptions for SC2181
Hi there,
Say we defined a function f()
in a subshell with set -e
, and call it with error check:
#!/usr/bin/env sh
f() (
set -e
echo Executing
false
echo Should NOT get HERE
)
f || echo Error
If we call it with f || echo Error
or if
statement as suggested in https://github.com/koalaman/shellcheck/wiki/SC2181 , the output will be:
Executing
Should NOT get HERE
Which is not what we want.
While this
f
[ "$?" -eq 0 ] || echo Error
works as expected, so I think this would be an exception.
Good practice is to avoid one-liner for future maintenance.
if ! f; then
In this case you can always add functionality without any refactoring (just adding lines)
For more complex error handling you have to store exit code into variable for case statement, etc
Had a similar issue.
I ended up making it work with traps, but that needs bash. I think traps are a bit nicer since it sidesteps the issue of checking $?
and the legitimate complaints associated with it from shellcheck.
That looks something like this, applying it to the original example:
#!/bin/bash
handle_error () (
echo "Handling error"
)
call_func () (
set -e
trap 'handle_error' ERR
echo "Executing"
false
echo "Should not get here"
)
call_func
To keep shellcheck quiet while using POSIX shell takes something similar to first store it in a variable:
#!/usr/bin/env sh
call_func () (
set -e
echo "Executing"
false
echo "Should not get here"
)
call_func
func_result=$?
if [ "$func_result" -ne 0 ]; then
echo "Handling error"
fi