I thought I know the shell, but I got bitten with unexpected behavior.
Consider this code:
#!/bin/bash
foo()
{
if false
then
echo success
else
return
fi
}
foo || echo failure
Now at first glance one would think the else return
part is superfluous, but it is not. The code as it is outputs failure
, but when the cited part is removed, then nothing is output.
The bash manual explains (for if
):
The exit status is the exit status of the last command executed, or zero if no condition tested true.
Somehow I'd expect the if
to fail when the command had failed.
Imagine where echo success
stands there are actually dependent commands that make only sense to execute when the main command (false
here) succeeded.
What is the logic behind that unexpected behavior?
Seen for bash-4.4. Related: https://stackoverflow.com/a/63884458/6607497