简体   繁体   中英

Bash convention for if ; then

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?

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 .

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.

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.

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
$ 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM