Bash convention for if ; then

二次信任 提交于 2019-12-04 06:44:43

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 c.u.s., you can read the replies here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!