Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some people put a semicolon after an if condition in shell scripts? [duplicate]

Tags:

bash

shell

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?

like image 216
Andy Avatar asked May 01 '18 13:05

Andy


People also ask

What happens if you put a semicolon after an if statement?

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.

What is the use of semicolon in shell script?

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.

What is double semicolon in shell script?

;; 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.

Do you need semicolons in shell script?

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.


1 Answers

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:

  • What's the difference between [ and [[ in Bash?
like image 135
John Kugelman Avatar answered Oct 21 '22 21:10

John Kugelman