在Array中声明变量

时间:2014-10-30 02:44:22

标签: arrays bash for-loop

所以我在使用数组声明变量时遇到了一些问题。 我希望为数组的每次迭代确定两个变量(STATUS和CONSUMERS)。

#!/bin/bash
QUEUE=( outbound.queue, inbound.queue, outbound.queue.optin )
DATE="$(date)"
MESSAGE="${QUEUE[$i]} is active with no Consumers at $DATE"
DESC="Please check rabbitmq for info on $HOSTNAME"
ALIAS="${QUEUE[$i]} $HOSTNAME"

for i in "${QUEUE[@]}"; do

    STATUS[$i]=$(sudo /usr/sbin/rabbitmqctl list_queues name status | grep "^${QUEUE[@]}\s" | sed "s/${QUEUE[@]}\s//")
    CONSUMERS[$i]=$(sudo /usr/sbin/rabbitmqctl list_queues name consumers | grep "^${QUEUE[@]}\s" | sed "s/${QUEUE[@]}\s//")

    if  [ "${STATUS[$i]}" = "running" ];
            then
            echo "$QUEUE[$i] is running";
                    if [ "${CONSUMERS[$i]}" = "0" ];
                    then
            lamp createAlert;
                    fi
            else
                    echo "$QUEUE is not running";
    fi
done

目前最终发生的事情是(取决于@或*在$ QUEUE []中)会尝试一次性使用所有变量,或者返回  line 13: outbound.queue: syntax error: invalid arithmetic operator (error token is ".queue")

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

代码中的一些评论;我无法检查,但希望它有所帮助。

#!/bin/bash

# remove commas from the list; separator is blank
QUEUE=(outbound.queue inbound.queue outbound.queue.optin)
DATE="$(date)"

# i is undefined. Use a printf at the time i is known.
MESSAGE="${QUEUE[$i]} is active with no Consumers at $DATE"
DESC="Please check rabbitmq for info on $HOSTNAME"
ALIAS="${QUEUE[$i]} $HOSTNAME"

for i in "${QUEUE[@]}"; do

    STATUS[$i]=$(sudo /usr/sbin/rabbitmqctl list_queues name status | grep "^${QUEUE[@]}\s" | sed "s/${QUEUE[@]}\s//")
    CONSUMERS[$i]=$(sudo /usr/sbin/rabbitmqctl list_queues name consumers | grep "^${QUEUE[@]}\s" | sed "s/${QUEUE[@]}\s//")

    if  [ "${STATUS[$i]}" = "running" ]   # ';' unnecessary
    then
        # {} were missing
        echo "${QUEUE[$i]} is running"
        if [ "${CONSUMERS[$i]}" = "0" ]
        then
           lamp createAlert
        fi
    else
        echo "$QUEUE is not running"
    fi
done

我无法理解for循环中i的值。它是整数还是队列名称? 如果是整数,你应该写for i in "${!QUEUE[@]}"; do;如果它是队列名称,则STATUSCONSUMERS是关联数组,您应该使用declare -A声明它们。