[bash] if空敘述

bash, if, null statement,

在bash中,條件的比對式中不能不寫任何指令,否則會出現錯誤

例如下面字串比對,先寫出了if條件式敘述但else保留空白不做任何事情

#!/bin/bash

name="Banana"

if [ "$name" = "Apple" ]; then
    echo "Name is Apple"
else

fi

執行後會看到下列錯誤

[root@localhost tutorial]# ./test01.sh 
./test01.sh: line 9: syntax error near unexpected token `fi'
./test01.sh: line 9: `fi'

需要加入空指令Null operator ":",讓程式知道不做任何事

#!/bin/bash

name="Banana"

if [ "$name" = "Apple" ]; then
    echo "Name is Apple"
else
    :
fi

很多人會用echo來解決這個問題

但如果你想用個空迴圈,則會造成一堆不必要的輸出