George
George

Reputation: 3619

Is semicolon optional at the end of if expression in bash script?

In bash script, the bracket quoted expression of an if statement has no semicolon to the right of ], according to the section Programming with Shell Scripts of this book.

But the semicolon can be seen at many different tutorials or scripts, such as this tutorial and this script snippet:

if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

When do I have to put semicolon there?

Upvotes: 1

Views: 902

Answers (1)

John Kugelman
John Kugelman

Reputation: 361655

If you want the then on the same line, then you need a semi-colon. If not, it's optional.

if x; then
    y
fi

if x
then
    y
fi

Think of it as how you write two commands. You can write either

foo
bar

or

foo; bar

Upvotes: 7

Related Questions