“期望一元运算符"如果条件,Bash中的错误 [英] "unary operator expected" error in Bash if condition

查看:105
本文介绍了“期望一元运算符"如果条件,Bash中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找出问题出在哪里,但根本无法解决..

I've been trying to figure out whats wrong with this but just can't figure it out..

这部分似乎出现错误.

elif [ $operation = "man" ]; then
    if [ $aug1 = "add" ]; then         # <- Line 75
    echo "Man Page for: add"
    echo ""
    echo "Syntax: add [number 1] [number 2]"
    echo ""
    echo "Description:"
    echo "Add two different numbers together."
    echo ""
    echo "Info:"
    echo "Added in v1.0"
    echo ""
elif [ -z $aug1 ]; then
    echo "Please specify a command to read the man page."
else
    echo "There is no manual page for that command."
fi

我收到此错误:

calc_1.2: line 75: [: =: unary operator expected

推荐答案

如果您始终使用bash,则始终使用双括号条件复合命令[[ ... ]]而不是Posix-兼容的单括号版本[ ... ].在[[ ... ]]复合物中,单词拆分和路径名扩展不适用于单词,因此您可以依靠

If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]], instead of the Posix-compatible single bracket version [ ... ]. Inside a [[ ... ]] compound, word-splitting and pathname expansion are not applied to words, so you can rely on

if [[ $aug1 == "and" ]];

$aug1的值与字符串and进行比较.

to compare the value of $aug1 with the string and.

如果使用[ ... ],则始终需要记住将变量用双引号引起来:

If you use [ ... ], you always need to remember to double quote variables like this:

if [ "$aug1" = "and" ];

如果您不引用变量扩展且变量未定义或为空,则它将从犯罪现场消失,仅留下

If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only

if [ = "and" ]; 

,这不是有效的语法. (如果$aug1包含空格或shell元字符,它也会失败,并显示不同的错误消息.)

which is not a valid syntax. (It would also fail with a different error message if $aug1 included white space or shell metacharacters.)

现代的[[运算符还具有许多其他不错的功能,包括正则表达式匹配.

The modern [[ operator has lots of other nice features, including regular expression matching.

这篇关于“期望一元运算符"如果条件,Bash中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆