遭遇"一元运算符预期"在bash脚本 [英] encounter "unary operator expected" in bash script

查看:211
本文介绍了遭遇"一元运算符预期"在bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的bash脚本,我有一个函数返回0或1(true或false)为后来的主要功能的状态。

in my bash script, I have a function to return 0 or 1(true or false) for the later main function's condition.

function1 () { 
    if [[ "${1}" =~ "^ ...some regexp... $" ]] ; then
        return 1
    else
        return 0
    fi 
}

然后在我的主要功能:

then in my main function:

main () { 
    for arg in ${@} ; do
        if [ function1 ${arg} ] ; then
            ...
        elif [ ... ] ; then
            ...
        fi
    done
}

然而,当我跑这个脚本,它总是给我一个错误味精[:功能1:一元运算符预期

however, when i ran this script it always gave me an error msg "[: function1: unary operator expected"

谁能帮助我吗?

推荐答案

您正在承担的常见的错误, [是一部分的如果命令的语法。不是这样;如果的的语法很简单:

You are making the common mistake of assuming that [ is part of the if command's syntax. It is not; the syntax of if is simply

if command; then
    ... things which should happen if command's result code was 0
else
    ... things which should happen otherwise
fi

一个常见的​​命令取值,我们使用 [这是命令<$ C $别名C>测试。它是对比较字符串,数字和文件的简单命令。它接受的参数一个相当狭窄的结合,容易产生混淆和误导的错误消息,如果你不把它传递预期的参数。 (或者说,该错误信息是充分的和有益的,一旦你习惯了它,但他们,如果你不使用容易被误解。)

One of the common commands we use is [ which is an alias for the command test. It is a simple command for comparing strings, numbers, and files. It accepts a fairly narrow combination of arguments, and tends to generate confusing and misleading error messages if you don't pass it the expected arguments. (Or rather, the error messages are adequate and helpful once you get used to it, but they are easily misunderstood if you're not used.)

在你的函数,调用 [出现错位。你可能意味着

In your main function, the call to [ appears misplaced.  You probably mean

if function "$arg"; then
    ...
elif ... ; then ...

顺便说一句,好措施,你也应该总是给你的字符串。使用$ 1不是 $ 1 $ ARG而不是 $ ARG

历史原因测试的东西一般厨房水槽的作者并不想如果的语法的一部分code>是原来的Bourne shell的不那么有吸引力的设计之一。 Bash和的zsh 提供替代这是不太笨重(如 [双括号在bash,你在用你的功能1 的定义),当然,POSIX 测试是一个很多比从贝尔实验室独创多好脾气

The historical reasons for test as a general kitchen sink of stuff the authors didn't want to make part of the syntax of if is one of the less attractive designs of the original Bourne shell. Bash and zsh offer alternatives which are less unwieldy (like the [[ double brackets in bash, which you use in your function1 definition), and of course, POSIX test is a lot more well-tempered than the original creation from Bell Labs.

作为一个额外的澄清,你的函数可以简化为只

As an additional clarification, your function can be simplified to just

function1 () {
    ! [[ "$1" =~ "^ ...some regexp... $" ]]
}

也就是说,执行与 [测试并扭转其结果code。 (正常的情况下,将成功返回0,但也许你正试图验证字符串不匹配?)

That is, perform the test with [[ and reverse its result code. (The "normal" case would be to return 0 for success, but maybe you are attempting to verify that the string doesn't match?)

这篇关于遭遇&QUOT;一元运算符预期&QUOT;在bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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