0

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
   cmd1
   cmd2
   cmd3
done
while true; do
   cmd1;
   cmd2;
   cmd3;
done

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

2
  • To save ink, you could also do while {} {cmd1;cmd2;cmd3} or for ((;;)){cmd1;cmd2;cmd3} but should you? Feb 3 at 9:23
  • That's the question. :-)
    – colinh
    Feb 3 at 17:34

1 Answer 1

4

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.

1
  • < unless you want to consider "Sina Bala's personal code guidelines" a rule. > That's good enough for me.
    – colinh
    Feb 3 at 17:34

Not the answer you're looking for? Browse other questions tagged .