我试图允许用户输入他们想要连接的ip地址的数量,然后输入每个ip地址并将其分配给变量。该脚本最终将编写并执行第二个脚本。第二个脚本的原因是我正在进入一个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
答案 0 :(得分:0)
如果不重写整个脚本,这里有一个片段。
#!/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
答案 1 :(得分:0)
阵列是你的朋友。请采取以下措施;
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
如果您使用该可选代码片段,您甚至不必询问用户想要的地址数。您可以将for
循环替换为while true; do
,并指示用户输入&#34; done&#34; (或任何其他退出命令)结束地址集合(尽管你需要在某处定义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