Bash convention for if ; then

2019-04-09 08:50发布

问题:

From this web page :

http://tldp.org/LDP/abs/html/abs-guide.html

It's mentioned the usage of the if bracket then convention which need a space after the semicolon :

;

Command separator [semicolon]. Permits putting two or more commands on the same line.

echo hello; echo there


if [ -x "$filename" ]; then    #  Note the space after the semicolon.
#+                   ^^
  echo "File $filename exists."; cp $filename $filename.bak
else   #                       ^^
  echo "File $filename not found."; touch $filename
fi; echo "File test complete."

Note that the ";" sometimes needs to be escaped.

Does anyone know where is this coming from and if this is needed at all by certain shells?

回答1:

This has become the style in the last few years:

if [ -x "$filename" ]; then
   echo "hi"
fi

However, back when dinosaurs like Burroughs and Sperry Rand ruled the earth, I learned to write if statements like this:

if [ -x "$filename" ]
then
    echo "hi"
fi

Then, you don't even need a semicolon.

The new style with then on the same line as the if started in order to emulate the way C and other programming languages did their if statements:

if (! strcmp("foo", "bar")) {
   printf "Strings equal\n";
}

These programming languages put the opening curly brace on the same line as the if.



回答2:

Semicolon ; is an operator (not a keyword, like braces { }or a bang !) in Shell, so it doesn't need to be delimited with white space to be recognized in any POSIX-compliant shell.

However, doing so improves readability (for my taste).

Semicolon needs to be escaped if you mean a symbol "semicolon", not an operator.



回答3:

The space after the semicolon is not required by the syntax for any shell I know of, but it's good style and makes the code easier to read.

I suppose the "sometimes needs to be escaped" wording refers to cases like echo foo\;bar, where you don't want the semicolon to be interpreted as a separator by the shell.



回答4:

I do not believe that the space should be necessary there. There's nothing about requiring spaces in the POSIX sh spec.

Empirically, the following works fine in both bash 4.1.5(1) and dash:

$ if true;then echo hi;else echo bye;fi
hi
$ 


回答5:

I've never came across a shell that required a space in that context. Just to make sure, I've asked on c.u.s., you can read the replies here.