美文网首页
shell脚本启动 :字符串判空有空格报错:binary ope

shell脚本启动 :字符串判空有空格报错:binary ope

作者: andycheng | 来源:发表于2021-09-16 10:26 被阅读0次

使用 -z-n 对一个变量判空时,需要注意若直接使用 [ -n ${ARG} ] 这种形式,若${ARG} 中有空格将会报错:

if [ -z $old_run_pid ];then
    echo "Process Non-existent !"
else
    kill -9 ${old_run_pid}
    mid_run_pid=$(ps ax|grep $path/run.sh|grep -v grep|awk '{print $1}')
    if [ -z ${mid_run_pid} ];then
        echo "Process Close Success !"
    else
        echo "Process Close Fail !"
        exit 1
    fi
fi

输出:

stop.sh: 21: [: 31016: unexpected operator

显然不对

解决方法,使用 [[ -n ${ARG} ]][ -n "${ARG}" ]
eg:

if [ -z "$old_run_pid" ];then
    echo "Process Non-existent !"
else
    kill -9 ${old_run_pid}
    mid_run_pid=$(ps ax|grep $path/run.sh|grep -v grep|awk '{print $1}')
    if [ -z "${mid_run_pid}" ];then
        echo "Process Close Success !"
    else
        echo "Process Close Fail !"
        exit 1
    fi
fi

相关文章

网友评论

      本文标题:shell脚本启动 :字符串判空有空格报错:binary ope

      本文链接:https://www.haomeiwen.com/subject/ckhrgltx.html