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