-bash: [: =: 预期的一元运算符。当没有给出参数时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42637238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:30:30  来源:igfitidea点击:

-bash: [: =: unary operator expected. when no parameter given

bashshell

提问by Elye

I have my shell script, myscript.shbelow

我有我的 shell 脚本,myscript.sh在下面

#!/bin/sh
if [  = "-r" ]; then
    echo "I am here"
fi

If I run with . myscript.sh -r, it works well with message I am here.

如果我使用. myscript.sh -r,它可以很好地处理 message I am here

But if I just run with . myscript.sh, it complaints

但如果我只是跑. myscript.sh,它会抱怨

-bash: [: =: unary operator expected

-bash: [: =: unary operator expected

What's missing in my script?

我的脚本中缺少什么?

回答by Bhakti Gandhi

You would need to add quotes around $1.

您需要在 1 美元左右添加报价。

if [ "" = "-r" ]; then
    echo "I am here"
fi

When $1 is empty you are getting if [ = "-r"] which is a syntax error.

当 $1 为空时,您会得到 if [ = "-r"] 这是一个语法错误。

回答by Slava Semushin

You have missed the quotes:

你错过了报价:

if [ "" = "-r" ]; then