用户输入以指定脚本中有多少变量,然后为每个变量分配一个值



我试图允许用户输入他们想要与之交互的IP地址数量,然后输入每个IP地址并将其分配给一个变量。 该脚本最终将编写并执行第二个脚本。 第二个脚本的原因是我正在 ssh 进入一个 AP 以便将 x 个 AP 聚集在一起,一旦 SSH 发生,bash/python 变量就不再通过(AP 有自己的语言(,所以它们必须在运行 ssh 脚本之前翻译成纯文本。 下面的代码功能但只允许 2 个 IP 地址(我不知道如何使用$cvar创建多个变量(,并且不允许我决定输入多少个 IP 地址:

#!/bin/bash
echo -e "How many AP's do you want to Cluster?:"
#this is the variable to define how many ips to ask for
read cvar 
echo -e "Enter last 2 digits of AP #1:"
read ip1
echo -e "Enter last 2 digits of AP #2:"
read ip2
#I want this to continue for x number of ip addresses(defined by $cvar)
echo -e "Enter a name for your Cluster:"
read cname
#code below is executed within the AP terminal(commands are unique to that shell)
echo "#!/bin/bash
ssh -T admin@192.168.0.$ip1 <<'eof'
configure
cluster
add $cname
add-member 192.168.0.$ip1 user ***** password ********
save
add-member 192.168.0.$ip2 user ***** password ********
save
exit
operate $cname
save
exit
" > ./2ndScript.sh
chmod a+x ./2ndScript.sh
/bin/bash ./2ndScript.sh

在不重写整个脚本的情况下,这里有一个片段。

#!/bin/bash
# IP is an array
IP=()
# Read number of IP Addresses to be read in
read -p "How many AP's do you want to Cluster?: " cvar
loop=1
while [ $loop -le $cvar ]
do
read -p "Enter last 2 digits of AP #${loop}: " IP[$loop]
loop=$((loop+1))
done

数组是你的朋友。采取以下措施;

echo -e "Enter last 2 digits of AP #1:"
read ip1
echo -e "Enter last 2 digits of AP #2:"
read ip2
#I want this to continue for x number of ip addresses(defined by $cvar)

我们可以创建一个for循环,然后为每个地址向数组添加一个元素。在这个for循环中,$i将告诉我们我们处于哪个周期,从 0 开始。由于它是自动递增的,我们可以使用它来指定要更新的数组索引。

for (( i=0; i<$cvar; i++ )); do
echo -e "Enter last 2 digits of AP #$((i+1)):"
read #With no arguments, read assigns the output to $REPLY
#optional; this allows the user to enter "done" to end prematurely
#if [[ $REPLY == "done" ]]; then break; fi
ip[$i]=$REPLY #ip is the name of the array, and $i points to the index
done

如果您使用该可选代码片段,您甚至不必询问用户想要多少个地址。您可以改为用while true; do替换for循环,只需指示用户输入"done"(或任何其他退出命令(以结束地址收集(尽管您需要在某处定义i=0,然后在循环结束时递增它如果您交换到while(。

现在,您有一个从${ip[0]}${ip[n]}排序的值列表,其中包含用户输入的所有地址。您可以稍后使用另一个for循环提取它们;

for ((i=0;i<${#ip[*]};i++)); do
#Insert code here. For example:
#echo "${ip[$i]} #echos the currently selected value of the array
#echo "${ip[$i]}" >> file.txt #appends file.txt with the current value
done

最新更新