2018年7月3日 星期二

【shell script】[ :Unexpected operator in shell

今天把一支寫好的script放到Ubuntu跑,原本在板子上的Linux上跑是沒有問題的,但在Ubuntu上Run出現了錯誤訊息,簡單的程式如下所示:

############## test.sh ################
#!/bin/sh

NAME="danny"
NUM=56

if [ $NAME == "david" ]; then
    echo "This is david"
else
    echo "This is danny"
fi

if [ $NUM -gt 48 ]; then
    echo "num great then 48"
fi
####################################

執行程式後的錯誤訊息:
./test.sh: 6: [: danny: unexpected operator


找了一下原因,原來是因為 sh的語法並沒有 "==" 這種語法,而是必須使用單一個"="

而"=="這語法,是bash在使用的

因此解決方法有兩個:

    1. 把程式第一行的 #!/bin/sh 改成 #!/bin/bash

    2. 把語法 "==" 改為 "="



2 則留言: