我遇到了“预期的一元运算符"在 Bash 脚本中 [英] I encountered "unary operator expected" in a Bash script
问题描述
在我的 Bash 脚本中,我有一个函数可以为后面的 main 函数的条件返回 0 或 1(真或假).
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
}
然后在我的 main 函数中:
Then in my main function:
main () {
for arg in ${@} ; do
if [ function1 ${arg} ] ; then
...
elif [ ... ] ; then
...
fi
done
}
然而,当我运行这个脚本时,它总是给我一条错误信息:
However, when I ran this script it always gave me an error message:
[: function1: 预期的一元运算符
[: function1: unary operator expected
我该如何解决这个问题?
How can I fix this?
推荐答案
您犯了一个常见的错误,认为 [
是 if
命令语法的一部分.它不是;if
的语法很简单
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
我们使用的常见command
之一是[
,它是命令test
的别名.这是一个用于比较字符串、数字和文件的简单命令.它接受相当狭窄的参数组合,并且如果您没有将预期的参数传递给它,则往往会产生令人困惑和误导性的错误消息.(或者更确切地说,一旦您习惯了错误消息就足够了并且很有帮助,但如果您不习惯,它们很容易被误解.)
One of the common command
s 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.)
在您的 main
函数中,对 [
的调用似乎放错了位置.你可能是说
In your main
function, the call to [
appears misplaced. You probably mean
if function "$arg"; then
...
elif ... ; then ...
顺便说一句,为了更好地衡量,您还应该始终引用您的字符串.使用 "$1"
而不是 $1
,使用 "$arg"
而不是 $arg
.
By the way, for good measure, you should also always quote your strings. Use "$1"
not $1
, and "$arg"
instead of $arg
.
test
作为一般厨房水槽的历史原因,作者不想成为 if
语法的一部分,是不太吸引人的设计之一原始的 Bourne 外壳.Bash 和 zsh
提供了不那么笨拙的替代方案(例如 bash 中的 [[
双括号,您在 function1
定义中使用),并且当然,POSIX test
比贝尔实验室的原创要好得多.
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... $" ]]
}
即用[[
进行测试,并反转其结果代码.(正常"情况是返回 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?)
这篇关于我遇到了“预期的一元运算符"在 Bash 脚本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!