42

Why put semicolons in one and not in another?

The result is the same

Code one

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

Code two

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

Semicolons in the second code are unnecessary?

When it is necessary to place semicolons?

PersianGulf
  • 10,850
Jhonathan
  • 3,605
  • 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 00: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 03:11

2 Answers2

39

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).

choroba
  • 47,233
9

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

if [ ... ]; then
   doit-it-then
else
   doit-it-else
fi

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.

numchrun
  • 508