如何创建包含或运算符的if语句来计算传入的第一个参数?
我从底部的链接中直接复制了示例,没有任何运气。我还复制了其他我在网上发现的失败的例子。
# not working
if [ "$1" = "restart" || "$1" = "reload"]; then
echo "you passed in $1"
exit 3
fi
# not working
if [[ "$1" = "restart" || "$1" = "reload"]]; then
echo "you passed in $1"
exit 3
# not working
if [ $1 = "restart" || $1 = "reload"]; then
echo "you passed in $1"
exit 3
fi
# not working
if [ $1 == "restart" || $1 == "reload"]; then
echo "you passed in $1"
exit 3
fi
# not working
if [ $1 == "restart" || $1 == "reload"]; then
echo "you passed in $1"
exit 3
fi
# not working
if [ "$1" = "restart" || "$1" = "reload" ]; then
echo "you passed in $1"
exit 3
fi
# not working
if [ "$1" == "restart"] || [ "$1" == "reload" ]; then
echo "you passed in $1"
exit 3
fi再加上我能找到的其他语法..。
我有以下错误之一
/etc/init.d/gitlab: 192: [: =: unexpected operator或
/etc/init.d/gitlab: 192: [: missing ]或
/etc/init.d/gitlab: 194: [: missing ]
/etc/init.d/gitlab: 194: [: ==: unexpected operator资源
http://tldp.org/LDP/abs/html/comparison-ops.html
How to do a logical OR operation in Shell Scripting
http://www.thegeekstuff.com/2010/06/bash-if-statement-examples/
发布于 2013-10-06 01:27:48
通常,你会这样做:
if [ "$1" = restart -o "$1" = reload ]; then上一个示例不起作用的原因很简单,因为test使用=进行等式测试,而不是==。如果你像这样写它,它会起作用:
if [ "$1" = restart ] || [ "$1" = reload ]; then作为记录,您获得错误[: missing ]的原因是shell抓取了您编写的||,并将其视为命令的结尾,因此[命令只在此之前获取参数,没有找到任何结束]。
另外,您必须确保在最后一个参数和]之间保留一个空格,因为终止的]需要是自己的参数,因此您需要shell来正确地分割它。
次要的是,您不需要引用restart和reload字符串。由于它们不包含空格或展开,引用它们是一个noop。
另一方面,这也适用于:
[[ "$1" == "restart" || "$1" == "reload" ]]但这是因为[[命令是一个与[完全独立(尽管类似)的命令,并且使用了完全不同的语法(实际上是一个内置的shell,这就是为什么shell不知道从其中抢夺||的原因)。
在Bash中,有关更多细节,请参见help test和help [[,包括-o运算符。
发布于 2013-10-06 01:30:52
这个应该适合你,但如果不是,你的case是另一个选择。
if [ "$1" = "restart" ] || [ "$1" = "reload" ]; then
echo "you passed in $1"
exit 3
fi如果您使用:
case "$1" in
'start')
echo "Starting application"
/usr/bin/start
;;
'stop')
echo "Stopping application"
/usr/bin/stop
;;
'restart')
echo "Usage: $0 [start|stop]"
;;
esac本例的语法是从http://www.thegeekstuff.com/2010/07/bash-case-statement/借用的。
https://stackoverflow.com/questions/19204449
复制相似问题