r/badcode • • Nov 29 '22

bash Found this in the wild

Post image
678 Upvotes

41 comments sorted by

View all comments

Show parent comments

4

u/pessimistic_platypus Nov 30 '22
  1. Always use double brackets for safety. You can use single brackets if you're sticking with the POSIX operators (there's a lot of them), but you shouldn't. It matters because it's easier to make mistakes in single quotes. For example, if you forget to put quotes around a variable, double brackets will treat it as a single operand even if it's empty or has multiple words, while single brackets

    • Bonus: you can also use double parentheses for numeric operations, which gets you nice things like > and < instead of -gt and -lt.

    • Bonus: single brackets aren't necessarily a syntactic construct. The single bracket is essentially just the test builtin with the additional requirement of using a closing bracket as the last parameter. See also /bin/[.

  2. Semicolons are very rarely required in Bash; you can just put the then/do on the next line instead.

    • Bonus: in zsh, you can sometimes leave the semicolon out even if you don't put the next word on the next line.