Reputation: 137
if i write this in a script it runs
if [[ 1 == 1 ]]
then
echo "true"
fi
but if I tried to replace newline with ; when using an active shell i get syntax error
if [[ 1 == 1 ]]; then; echo "true"; fi
why?
what is the difference between hitting enter
after then
and ;
Upvotes: 1
Views: 46
Reputation: 85767
The bash manual says:
In most cases a list of commands in a compound command’s description may be separated from the rest of the command by one or more newlines, and may be followed by a newline in place of a semicolon.
The syntax of the
if
command is:if test-commands; then consequent-commands; [elif more-test-commands; then more-consequents;] [else alternate-consequents;] fi
(I believe the formatting in the above description (multiple lines, indentation) is for the benefit of the human reader, not part of the formal syntax. That is, if test-commands; then consequent-commands; [elif more-test-commands; then more-consequents;] [else alternate-consequents;] fi
would have the same meaning.)
The initial statement says ;
in this description can be replaced by a newline, but not vice versa.
Instead it says you can optionally put newlines before and after the command lists, which are simply ignored.
Taking your example:
if [[ 1 == 1 ]]
then
echo "true"
fi
Here we have test-commands of [[ 1 == 1 ]]
. The syntax requires a ;
, but because of the "may be followed by a newline in place of a semicolon" rule, we're fine (there is a following newline).
For the then consequent-commands;
part, we have
then
echo "true"
This is fine because the consequent-commands (i.e. echo "true"
) "may be separated from the rest of the command [i.e. then
in this case] by one or more newlines".
Again, the syntax requires a ;
next, but instead we use a newline, as permitted by the initial rule.
Then we reach the fi
and we're done.
Upvotes: 1