为什么有些人在shell脚本中的if条件后面加上分号? [英] Why do some people put a semicolon after an if condition in shell scripts?
问题描述
我刚刚习惯了shell脚本编写,并且遇到了一些我不太确定如何使用Google的内容.
I'm just getting used to shell scripting, and I've come across something which I'm not really sure how to google.
在我阅读的教程中,它表明编写if语句的正确方法是这样的:
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
我也看到过双方括号:
if [[ $a == $b ]]; then
echo "a == b"
fi
当我在bash中测试了所有这些功能后,似乎没有什么区别.有区别吗?它与兼容性有关吗?什么是正确的风格?
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?
推荐答案
if [ $a == $b ]; then
echo "a == b"
fi
您可以使用分号,也可以在单独的行上写then
.允许任何一个.
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:
这篇关于为什么有些人在shell脚本中的if条件后面加上分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!