#!/usr/bin/env bash
test_crash ()
{
a=$((009+1))
}
test_crash
if [[ $? -ne 0 ]] ; then
echo "case 1"
fi
test_crash ; if [[ $? -ne 0 ]] ; then
echo "case 1-1"
fi
The second method above also won't work. Isn't the purpose of a semicolon
to create a new line? Does it have some other side effect?
Andreas Kähäri <[email protected]> 于2026年2月2日周一 22:11写道:
> On Mon, Feb 02, 2026 at 09:22:04PM +0800, 王伟 wrote:
> > #!/usr/bin/env bash
> >
> > test_crash ()
> > {
> > a=$((009+1))
> > }
> >
> > test_crash
> > if [[ $? -ne 0 ]] ; then
> > echo "case 1"
> > fi
> >
> > if ! test_crash ; then
> > echo "case 2"
> > fi
> >
> > test_crash || echo "case 3"
> >
> > { test_crash ; } || echo "case 4"
> >
> > exit 0
> >
> > The code above shows the different results of several methods when a
> > function crashes due to a syntax error.
> >
> > pc@DESKTOP-0MVRMOU UCRT64 /d/code$ bash test_bash_broke.sh
> > test_bash_broke.sh: line 5: 009: value too great for base (error token is
> > "009")
> > case 1
> > test_bash_broke.sh: line 5: 009: value too great for base (error token is
> > "009")
> > test_bash_broke.sh: line 5: 009: value too great for base (error token is
> > "009")
> > test_bash_broke.sh: line 5: 009: value too great for base (error token is
> > "009")
> > pc@DESKTOP-0MVRMOU UCRT64 /d/code$
> >
> > Why is the exception branch executed only in the case of $?, and skipped
> in
> > all other cases?
>
> Because only in the 1st case does the shell set $? to a non-zero exit
> status after the function call fails.
>
> In the other cases, the function call itself is part of a conditional
> construct, and the failure of the function call causes the conditional
> construct to fail.
>
> Note that the functon is never executed successfully. If you inserted
> further commands after the line with the arithmetic error, those
> commands would never be executed. The function never really returns a
> value, because it never completes. In the 2nd, 3rd, and 4th cases, the
> shell simply treats the failure of the function call as a failure of the
> entire conditional construct.
>
> The above is a bit of handwaving. The manual says:
>
> If expression is invalid, bash prints a message to standard
> error indicating failure, does not perform the substitution, and
> does not execute the command associated with the expansion.
>
> The "command associated with the expansion" is the function call in the
> 1st case, and the entire conditional construct in the other cases.
>
> --
> Matti Andreas Kähäri
> Uppsala, Sweden
>
> .
>