我根据群集中的节点生成文本文件。
cat primary_nodes.txt
clusterNodea
clusterNodeb
..
....
clusterNoden
当我尝试为每一行生成变量时,它会给我以下输出
while read PRIMARY_NODE$((i++)); do
echo $PRIMARY_NODE1
echo $PRIMARY_NODE2
done < primary_node.txt
clusterNodea
clusterNodea
clusterNodeb
我想要的是:
答案 0 :(得分:2)
在bash 4中:
readarray -t primary_node <primary_node.txt
此后:
echo "${primary_node[0]}" # clusterNodea
echo "${primary_node[1]}" # clusterNodeb
或者迭代值:
for node in "${primary_node[@]}"; do
echo "Processing node $node"
done
i=0
while IFS= read -r line; do
printf -v "primary_node$((i++))" '%s' "$line"
done <primary_node.txt
echo "$primary_node1"
答案 1 :(得分:0)
阵列是你的朋友:
readarray -t MYARRAY <primary_nodes.txt
$ echo ${MYARRAY[0]}
clusterNodea
$ echo ${MYARRAY[1]}
clusterNodeb
请注意,也可以使用以下内容:
$ MYARRAY=($(cat primary_nodes.txt))
然而这应该避免因为文件通配和文字空格可以给出意想不到的结果,正如Charles Duffy在下面指出的那样
答案 2 :(得分:0)
使用declare
和间接扩展进行动态变量分配
#!/bin/bash
i=1
while IFS= read -r line; do
# The 'declare' syntax creates variables on the fly with the values
# read from the file
declare primaryNode$((i++))="$line"
done <file
count="$((i-1))"
# Now the variables are created; those can be individually accessed as
# '$primaryNode1'..'$primaryNoden'; but to print it on a loop, use
# indirect expansion using ${!var} syntax
for ((idx=1; idx<=count; idx++)); do
temp=primaryNode$idx
printf "PRIMARY NODE%s=%s\n" "$idx" "${!temp}"
done