-
Notifications
You must be signed in to change notification settings - Fork 94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Why to always use "if [[ ... ]]; then; fi" instead of a conditional statement #22
Comments
Like, my boilerplate header in Plushu is
and right now I'm considering changing that, because if the rest of the file is empty and tracing isn't enabled, this will crash its caller. (And then you have a wonderful Heisenbug where the problem only manifests itself when debugging isn't on!) |
If the rest of the file is empty? When would you have a script that has nothing but this? Otherwise, it seems totally reasonable to understand this behavior. I can imagine maybe a tip to remind people that this happens, but I don't think it's worth a rule against conditional expressions. |
When I'm creating stub scripts before filling them in.
Okay, so in the middle of responding to a long-standing issue that's been sitting in the queue for weeks/months/years, you're refactoring a file that does this at the end: [[ -f "$EXTRA_STUFF_FILE" ]] && cat "$EXTRA_STUFF_FILE"
printf "FINAL_VAR=%q\n" "$(finalization_code)" To do this instead: printf "FINAL_VAR=%q\n" "$(finalization_code)"
[[ -f "$EXTRA_STUFF_FILE" ]] && cat "$EXTRA_STUFF_FILE" Is this specific combination of caveats (that Bash exits with the last exit code normally, and that (Hint: I went through this 36 hours ago. It's the second one.) |
Curious about your debugging process for this ... if you had tracing on, wouldn't that lead to this line? I guess not if your outer scripts suppress the nonzero exit? I'm imagining that |
Except tracing doesn't show any difference between tests inside conditions and tests outside them, so all you see is a series of Or you could just take the ten extra keystrokes it takes to type |
Not to mention always using |
Okay, I'm starting to see the light... |
Statements joined with
&&
don't end a script even when it's running withset -e
, but if they're the last statement in your file, their non-zero exit code will be your script's exit code (think of it like an implicitreturn
), and if that script was getting called by something withset -e
, the whole house of cards will come tumbling down.In other words, while it's an easily-avoided ledge, it still needs a railing, because a single careless bump will send you way the hell crash tumbling down.
I used to remember this pitfall, but then I went away for a few months, and when I came back I couldn't remember why I didn't do this, and I did it all over my code, and immediately got bitten by this. In general, if you're using
set -e
, only use tests to test things.The text was updated successfully, but these errors were encountered: