Why put semicolons in one and not in another?

The result is the same

Code one

if [ "a" == "a" ]
 echo "true"

Code two

if [ "a" == "a" ];
 echo "true";

Semicolons in the second code are unnecessary?

When it is necessary to place semicolons?

  • 2
    This has been sufficiently and properly answered, but I wanted to let the OP also know that ; just replaces any end-of-line, so you can combine two commands into one line, e.g.: svn up; make – Aaron D. Marasco Sep 22 '12 at 0:54
  • 1
    Note also that two semi-colons ;; are used to separate matches in case statements. ;; is required here, not optional....but ;; isn't the same thing as ; or ; ;, it just looks a bit like it. Single semi-colons ; work as normal in the COMMANDS parts of a case statements. – cas Sep 22 '12 at 3:11

The semicolon is needed only when the end of line is missing:

if [ "a" == "a" ] ; then echo "true" ; fi

Without semicolons, you get Syntax error.

I do not understand your question about quotes. Can you be more specific?

(And by the way, using = instead of == is more portable and POSIX compliant).

  • Quotes in the second code are unnecessary? – Jhonathan Sep 21 '12 at 19:17
  • 3
    All the quotes in both the samples are unnecessay. – choroba Sep 21 '12 at 19:41

The semicolon is often used, because some folks (/me e.g.) like a style like this:

if [ ... ]; then

So, if the then-keyword is placed on the condition-line then it is neccessary because a new command starts, as written by choroba.

Concerning the quotes in the condition-check they are often used with variables to make sure no exception occurs if nothing is assigned to the variable. This is a safer style and looks unneccessary, but even in shell-programming it has from time to time made programs process though contents couldn't be assigned to variables. Then the command is still working because an empty string is compared.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.