Linux [ :shell 编程中的意外操作符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3411048/
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
[ :Unexpected operator in shell programming
提问by kit.yang
My code:
我的代码:
#!/bin/sh
#filename:choose.sh
read choose
[ "$choose" == "y" -o "$choose" == "Y" ] && echo "Yes" && exit 0
[ "$choose" == "n" -o "$choose" == "N" ] && echo "No" && exit 0
echo "Wrong Input" && exit 0
But when I execute
但是当我执行
sh ./choose.sh
terminal prompt me that
终端提示我
[: 4: n: :Unexpected operator
[: 5: n: :Unexpected operator
Is there any mistake in my bash script? Thanks!
我的 bash 脚本有什么错误吗?谢谢!
采纳答案by Wolph
There is no mistake in your bashscript. But you are executing it with shwhich has a less extensive syntax ;)
您的bash脚本中没有错误。但是您正在使用sh执行它,它的语法不太广泛;)
So, run bash ./choose.sh
instead :)
所以,bash ./choose.sh
改为运行:)
回答by Anycorn
you have to use bash instead or rewrite your script using standard sh
您必须改用 bash 或使用标准 sh 重写您的脚本
sh -c 'test "$choose" = "y" -o "$choose" = "Y"'
回答by Hyman Scott
To execute it with Bash, use #!/bin/bash and chmod it to be executable, then use
要使用 Bash 执行它,请使用 #!/bin/bash 并将其 chmod 使其可执行,然后使用
./choose.sh
回答by Nietzche-jou
POSIX shdoesn't understand ==
for string equality, as that is a bash-ism. Use =
instead.
POSIX sh不理解==
字符串相等,因为那是bash主义。使用=
来代替。
The other people saying that brackets aren't supported by share wrong, btw.
其他人说sh不支持括号是错误的,顺便说一句。
回答by delatbabel
In fact the "[" square opening bracket is just an internal shell alias for the test command.
事实上,“[”方括号只是 test 命令的内部 shell 别名。
So you can say:
所以你可以说:
test -f "/bin/bash" && echo "This system has a bash shell"
or
或者
[ -f "/bin/bash" ] && echo "This system has a bash shell"
... they are equivalent in either sh or bash. Note the requirement to have a closing "]" bracket on the "[" command but other than that "[" is the same as "test". "man test" is a good thing to read.
...它们在 sh 或 bash 中是等效的。请注意,要求在“[”命令上有一个结束的“]”括号,但除此之外,“[”与“test”相同。“男人测试”是个好东西。
回答by ghostdog74
you can use case/esac instead of if/else
你可以使用 case/esac 而不是 if/else
case "$choose" in
[yY]) echo "Yes" && exit;;
[nN]) echo "No" && exit;;
* ) echo "wrong input" && exit;;
esac
回答by Ap.Muthu
Do not use any reserved keyword as the start of any variable name: eg HOSTNAME will fail as HOST {TYPE|NAME} are reserved
不要使用任何保留关键字作为任何变量名的开头:例如 HOSTNAME 将失败,因为 HOST {TYPE|NAME} 被保留