“意外的运算符"来自[$ var -eq 1] [英] "Unexpected operator" from [ $var -eq 1 ]
问题描述
我在bash脚本中使用了这个条件
if [$ USE_TEST -eq 1];然后回声你好"科幻
我在其中传递 USE_TEST
作为环境变量.
如果我传递env变量,那么shell将执行正常,但是如果我没有该变量,那么我会得到这个
[:-eq:意外的运算符
我该如何解决
这是引号很重要的事情之一;当未定义$ USE_TEST时,您的语句将扩展为:
if [-eq 1];然后
常用解决方法:
if ["$ USE_TEST" -eq 1];然后
...尽管这也意味着切换到字符串比较,因为 -eq
将以空字符串中断:
如果[[$ USE_TEST"= 1];然后
但是您也可以考虑使用 [[
(这是内置的bash)或 $ {USE_TEST:-0}
(指定默认值).>
I am using this conditional in my bash script
if [ $USE_TEST -eq 1 ]; then
echo "Hello"
fi
where i pass USE_TEST
as an environment variable.
If i pass env variable then shell executes ok but if i don't have that variable then i get this
[: -eq: unexpected operator
How can i fix that
This is one of those matter where quotes are important; when $USE_TEST is not defined, your statement expands to:
if [ -eq 1 ]; then
The common fix:
if [ "$USE_TEST" -eq 1 ]; then
...though that would also imply switching to a string comparison, because -eq
will break with an empty string:
if [ "$USE_TEST" = 1 ]; then
But you may also consider using [[
(which is a bash builtin) or ${USE_TEST:-0}
(which specifies a default value).
这篇关于“意外的运算符"来自[$ var -eq 1]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!