I'm just getting used to shell scripting, and I've come across something which I'm not really sure how to google.
In the tutorials I was reading, it suggests that the correct way to write an if statement is like this:
if [ $a == $b ]; then
echo "a == b"
fi
However I've seen in our code base places where the semi colon is omitted:
if [ $a == $b ] then
echo "a == b"
fi
I've also seen double square brackets:
if [[ $a == $b ]]; then
echo "a == b"
fi
When I've tested all of these in bash, there doesn't seem to be a difference. Is there a difference? Does it have to do with compatibility? What is the correct style to adopt?
The semi-colon in the if indicates the termination of the if condition as in java ; is treated as the end of a statement, so the statement after if gets executed.
Answer. The semi-colon (;) is a standard UNIX shell item used to separate commands. The overall return code will be true even if it did not succeed, that is, if there were no files to remove.
;; is only used in case constructs, to indicate the end of an alternative. (It's present where you have break in C.) case $answer in yes) echo 'yay!' ;; no) echo 'boo!' ;; esac.
A semicolon or ampersand ( ; or & ) in a shell script is a command terminator. You can't use it if it doesn't follow a command. ; means “run the preceding command in the foreground” and & means “run the preceding command in the background”. A newline in a shell script is a “weak” command terminator.
if [ $a == $b ]; then
echo "a == b"
fi
You can use a semicolon, or you can write then
on a separate line. Either one is allowed.
if [ $a == $b ]
then
echo "a == b"
fi
Having neither a ;
nor a newline is a syntax error.
$ if [ $a == $b ] then
> echo "a == b"
> fi
bash: syntax error near unexpected token `fi'
As for [
vs [[
, see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With