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

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

问题描述

此脚本出错:

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 中的错误 if 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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