Here's another way to explain the need for a line break or semicolon before then
: the thing that goes between if
and then
is a command (or sequence of commands); if the then
just came directly after the command without a delimiter, it'd be ambiguous whether it should be treated as a shell keyword or just an argument to the command.
For instance, this is a perfectly valid command:
echo This prints a phrase ending with then
...which prints "This prints a phrase ending with then". Now, consider this one:
if echo This prints a phrase ending with then
should that print "This prints a phrase ending with then" and look for a then
keyword later on, or should it just print "This prints a phrase ending with" and treat the then
as a keyword?
In order to settle this ambiguity, shell syntax says it should treat "then" as an argument to echo
, and in order to get it treated as a keyword you need a command delimiter (line break or semicolon) to mark the end of the command.
Now, you might think that your if
condition [ $1 -gt 0 ]
, already has a perfectly good delimiter, namely the ]
. But in shell syntax, that's really just an argument to the [
command (yes, that's a command). Try this command:
[ 1 -gt 0 ] then
...and you'll probably get an error like "-bash: [: missing ']'", because the [
command checked its last argument to make sure it was "]", found that it was "then" instead, and panicked.