29

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?

Andy
  • 3,228
  • 8
  • 40
  • 65
  • 2
    This might help: `help if` – Cyrus May 01 '18 at 13:28
  • For [ vs [[, look at this page: http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Blocks_.28if.2C_test_and_.5B.5B.29, section 4. Conditional Blocks – Nic3500 May 01 '18 at 13:40
  • 4
    One other minor note is that `==` is a bash-specific comparison operator. Using just one `=` is the POSIX-compliant way of comparing strings. You likely also want to double-quote your variables to avoid unintended word-splitting, so `if [ "$a" = "$b" ]`. – John Moon May 01 '18 at 14:11

1 Answers1

48
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:

jub0bs
  • 60,866
  • 25
  • 183
  • 186
John Kugelman
  • 349,597
  • 67
  • 533
  • 578