init脚本`或`操作数

时间:2013-10-06 01:24:39

标签: bash if-statement

如何创建包含or运算符的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

https://unix.stackexchange.com/questions/47584/in-a-bash-script-using-the-conditional-or-in-an-if-statement

How to do a logical OR operation in Shell Scripting

http://www.thegeekstuff.com/2010/06/bash-if-statement-examples/

2 个答案:

答案 0 :(得分:4)

通常,你会这样做:

if [ "$1" = restart -o "$1" = reload ]; then

您的上一个示例不起作用的原因仅仅是因为test使用=进行相等性测试,而不是==。如果你这样写它,它可以工作:

if [ "$1" = restart ] || [ "$1" = reload ]; then

对于记录,您收到错误[: missing ]的原因是因为shell会抢占您编写的||,并将其视为命令的结尾,因此{{1有问题的命令只会在此之前获取参数,而不是找到任何结尾[

此外,您必须确保在最后一个参数和]之间保留一个空格,因为终止]需要是它自己的参数,因此您需要shell正确拆分。

除此之外,您无需引用]restart字符串。由于它们不包含空格或扩展,因此引用它们是一种noop。

另一方面,这也有效:

reload

但那是因为[[ "$1" == "restart" || "$1" == "reload" ]] 命令是[[的一个完全独立的(虽然相似)命令,并使用完全不同的语法(实际上是内置的shell,这就是shell知道的原因不要从中抢夺[

在Bash中,请参阅||help test了解更多详情,包括help [[运营商。

答案 1 :(得分:0)

这个应该适合你,但如果没有,你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/