Zsh: What is the idiomatic way of terminating lines in a script? (semicolon, new-line)

I’m fairly comfortable with putting semicolons, newlines and ampersands where they’re needed. But what is the "correct" way? Is it just a matter of style/personal preference, or is one in some way better than the other?

while true; do
while true; do

The second one uses more ink/electrons, but you could simply join the lines and it would still be ok:

while true; do cmd1; cmd2; cmd3; done

Asked By: colinh


The Lexer/Parser doesn’t see these as different.

You never just randomly join lines, that doesn’t make the least sense, so you’re not really solving a real-world issue there.

So all differences are human-perceptive.

I’d personally advocate for the style with each command clearly visible on its own line, no semicolon, unless syntactically relevant, out of the experience that the other code is more likely to contain easy-to-miss mistakes. (Which is because it’s beginners that randomly sprinkle meaningless elements like the semicolons, and beginners’ codes are more likely to be erroneous. On a causal side, if you add elements to your code that neither syntactically matter nor clarify an intention behind what was already obvious, my brain has to explicitly ignore them, and will have less capacity to find actual problems with your code.)

But that’s purely a preference, and there’s nothing "correct" about it, unless you want to consider "Sina Bala’s personal code guidelines" a rule.

All in all, though, consistency beats the crap out of any "I like that" reasoning. If you write shell scripts, use an editor that does the indentation and some limited syntax highlighting and checking for you. If that editor automatically adds a semicolon to the end of each line, or marks a line missing one: fine! But nothing’s worse than reading code where one third of the lines follow a different convention than the others. Makes the readers’ minds occupied with learning the structure of every line anew, instead of learning the content and logic of the script.

Answered By: sina bala
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.