for SLAVE_CLUSTER,MASTER_CLUSTER in $MASTER_CLUSTERS $SLAVE_CLUSTERS
do
echo "Master cluster boxes are ${!MASTER_CLUSTER}"
echo "Slave cluster boxes are ${!SLAVE_CLUSTER}"
done
我试图在一个 for 循环中获取SLAVE_CLUSTER
,的值,MASTER_CLUSTER
但出现错误。我们怎样才能在一个for
循环中同时获取这两个变量呢?
这是我的主从集群变量
export MASTER_CLUSTER_1="MASTER1 MASTER2"
echo "MASTER_CLUSTER_1 = $MASTER_CLUSTER_1"
export MASTER_CLUSTER_2="MASTER1 MASTER2"
echo "MASTER_CLUSTER_2 = $MASTER_CLUSTER_2"
export SLAVE_CLUSTER_1="SLAVE1 SLAVE2 SLAVE3 SLAVE4"
echo "SLAVE_CLUSTER_1 = $SLAVE_CLUSTER_1"
export SLAVE_CLUSTER_2="SLAVE1 SLAVE2 SLAVE3 SLAVE4"
echo "SLAVE_CLUSTER_2 = $SLAVE_CLUSTER_2"
答案1
我不确定我是否理解您对单个循环的需求。您可以使用这样的两个连续循环获得相同的输出
for MASTER_CLUSTER in $MASTER_CLUSTERS
do
echo "Master cluster boxes are ${!MASTER_CLUSTER}"
done
for SLAVE_CLUSTER in $SLAVE_CLUSTERS
do
echo "Slave cluster boxes are ${!SLAVE_CLUSTER}"
done
或者如果这些值必须交替,那么
for MASTER_CLUSTER in $MASTER_CLUSTERS
do
echo "Master cluster boxes are ${!MASTER_CLUSTER}"
for SLAVE_CLUSTER in $SLAVE_CLUSTERS
do
echo "Slave cluster boxes are ${!SLAVE_CLUSTER}"
done
done
答案2
根据OP的澄清扩展我的答案。同样,您可以使用数组:
$ cat /tmp/foo.sh
#/bin/bash
# Sample values from OP
export MASTER_CLUSTER_1="MASTER1 MASTER2"
export MASTER_CLUSTER_2="MASTER3 MASTER4" # (edited to be unique)
export SLAVE_CLUSTER_1="SLAVE1 SLAVE2 SLAVE3 SLAVE4"
export SLAVE_CLUSTER_2="SLAVE5 SLAVE6 SLAVE7 SLAVE8" # (edited to be unique)
# Create two arrays, one for masters and one for slaves. Each array has
# two elements -- strings containing space delimited hosts
declare -a master_array=( "${MASTER_CLUSTER_1}" "${MASTER_CLUSTER_2}" )
declare -a slave_array=( "${SLAVE_CLUSTER_1}" "${SLAVE_CLUSTER_2}" )
# For this to work, both arrays need to have the same number of elements
if [[ "${#master_array[@]}" == ${#slave_array[@]} ]]; then
for ((i = 0; i < ${#master_array[@]}; ++i)); do
echo "master: ${master_array[$i]}, slave: ${slave_array[$i]}"
done
fi
示例输出:
$ bash /tmp/foo.sh
master: MASTER1 MASTER2, slave: SLAVE1 SLAVE2 SLAVE3 SLAVE4
master: MASTER3 MASTER4, slave: SLAVE5 SLAVE6 SLAVE7 SLAVE8