腳本報錯:unary operator expected

腳本執行,出現以下錯誤:「h.sh: line 9: [: ==: unary operator expected」,具體腳本以下:vim

[root@Dasoncheng sbin]# cat -n h.sh 
     1	#!/bin/bash
     2	sh -n $1 &>/tmp/err
     3	if [ $? -eq 0 ];
     4	then
     5	    echo "The script is ok"
     6	else
     7	    cat /tmp/err
     8	    read -p "Please input q/Q to exit , or others to edit it by vim: " n
     9	    if [ $n == "q" ] || [ $n == "Q" ];
    10	    then
    11	        exit
    12	    else
    13	        vim $1
    14	        exit
    15	    fi
    16	fi
[root@Dasoncheng sbin]# sh h.sh i.sh 
i.sh: line 3: syntax error: unexpected end of file
Please input q/Q to exit , or others to edit it by vim: 
h.sh: line 9: [: ==: unary operator expected
h.sh: line 9: [: ==: unary operator expected  ##這個就是執行的報錯信息;

解決辦法:bash

if [ $n == "q" ] || [ $n == "Q" ];修改成:if [ "$n" == "q" ] || [ "$n" == "Q" ];
##便可;

由於當$n爲空值時(即回車 未輸入任何參數),那麼就成了 [ = "q"]了,顯然缺乏了對比參數。當$n值不爲空時,腳本仍是正常的;
使用以下幾種方法,也能夠避免:code

if [[ $n == "q" ]] || [[ $n == "Q" ]]
##或者
if [ "$n"x == "q"x ] 
##其中x也能夠爲其餘字符;
相關文章
相關標籤/搜索