if的Bash约定; 然后

Chm*_*nah 6 bash shell coding-style

从这个网页:

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

它提到了if括号然后约定的用法,它在分号后需要一个空格:

;

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.
Run Code Online (Sandbox Code Playgroud)

有谁知道这是从哪里来的,如果某些贝壳需要它?

Dav*_* W. 13

这已成为过去几年的风格:

if [ -x "$filename" ]; then
   echo "hi"
fi
Run Code Online (Sandbox Code Playgroud)

然而,当Burroughs和Sperry Rand等恐龙统治地球时,我学会了写下这样的陈述:

if [ -x "$filename" ]
then
    echo "hi"
fi
Run Code Online (Sandbox Code Playgroud)

然后,你甚至不需要分号.

为了模仿方式和其他编程语言完成了他们的语句,新的样式与then启动的行相同:ifCif

if (! strcmp("foo", "bar")) {
   printf "Strings equal\n";
}
Run Code Online (Sandbox Code Playgroud)

这些编程语言将开头大括号放在与...相同的行上if.


Rom*_*aka 9

分号;是Shell中的运算符(不是关键字,如大括号{ }或爆炸!),因此不需要在任何符合POSIX的shell中使用空格分隔.

但是,这样做可以提高可读性(根据我的口味).

如果你的意思是象征"分号"而不是运算符,则需要转义分号.