[: bash 脚本中缺少‘]’
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35281797/
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
[: missing `]' in bash script
提问by Majora320
So I'm writing a bash shell script, and my first few lines looks like this:
所以我正在编写一个 bash shell 脚本,我的前几行如下所示:
if ! [ $# -eq 0 || $# -eq 1 ]; then
echo -e "Usage: myScriptName [\e[3mdir\e[0m] [\e[3m-f file\e[0m]"
exit 1
fi
But when I run it, it says "[: missing `]'". I don't see a missing ], and nothing except the ; is touching the ], so what am I missing?
但是当我运行它时,它说“[:缺少`]'”。我没有看到丢失的 ],除了 ; 正在触摸],所以我错过了什么?
回答by kojiro
You cannot use operators like ||
within single-brace test expressions. You must either do
您不能像||
在单大括号测试表达式中那样使用运算符。你必须要么做
! [[ $# -eq 0 || $# -eq 1 ]]
or
或者
! { [ $# -eq 0 ] || [ $# -eq 1 ]; }
or
或者
! [ $# -eq 0 -o $# -eq 1 ]
The double-brace keyword is a bash expression, and will not work with other POSIX shells, but it has some benefits, as well, such as being able to do these kinds of operations more readably.
双括号关键字是一个 bash 表达式,不能与其他 POSIX shell 一起使用,但它也有一些好处,例如能够更易读地执行这些类型的操作。
Of course, there are a lot of ways to test the number of arguments passed. The mere existence of $2
will answer your question, as well.
当然,有很多方法可以测试传递的参数数量。的存在也$2
将回答您的问题。