bash问题1: if test-commds; then consequent-commands fi 这里的then有什么用?

bash问题1: if test-commds; then consequent-commands fi 这里的then有什么用?

if test-commands
then
  consequent-commans;
fi

为什么bash的设计者要加一个then呢?我觉得不加then依然可以表示这个if的逻辑

if test -commands
consequent-commands
fi 

这些都是探讨,突发奇想
先写一个能运行的if脚本:


a=0
b=1
if [[ a -eq 0 ]] && [[ b -eq 1 ]];
then
echo "a == 0 && b == 1"
fi

b=0
if [[ a -eq 0 ]] && [[ b -eq 1 ]];
then
    echo "yes"
else
    echo "no"
fi



运行这个脚本:

lkmao@ubuntu:~$ bash if.sh
a == 0 && b == 1
no
lkmao@ubuntu:~$



然后再去掉第一个then,看看报错是什么?

a=0
b=1
if [[ a -eq 0 ]] && [[ b -eq 1 ]];
#then
echo "a == 0 && b == 1"
fi

b=0
if [[ a -eq 0 ]] && [[ b -eq 1 ]];
then
    echo "yes"
else
    echo "no"
fi


执行报错如下:这说明,fi会找then配对

lkmao@ubuntu:~$ bash if.sh
if.sh: line 6: syntax error near unexpected token `fi'
if.sh: line 6: `fi'
lkmao@ubuntu:~$


img

然后再将第10行的then注释掉

img

这个得出一个什么样的结论呢?bash程序,碰到if就会入栈,一直入栈,然后碰到fi或者else,开始出栈操作,出栈的时候,找then语句,如果在找到if之前,没有找到then,就报错,if后面可以没有分好,但是不能没有then。
再看一个极端的东西:如下所示,如果没有then,if后面可以无限长,可能根本不知道条件判断到哪里结束

a=0
b=1
if [[ a -eq 0 ]] && [[ b -eq 1 ]];
then
echo "a == 0 && b == 1"
fi

b=0
if [[ a -eq 0 ]] && [[ b -eq 1 ]] || echo "hello" ;echo "world"
then
    echo "yes"
else
    echo "no"
fi


而且,这个脚本时能正常工作的

lkmao@ubuntu:~$ bash if.sh
a == 0 && b == 1
hello
world
yes
lkmao@ubuntu:~$


语法规定,if条件 then满足条件后执行的命令