![使用文件中的主机地址生成 shellscript 菜单,并在每个选项下方显示带有“ping 状态”的选项?](https://linux22.com/image/230966/%E4%BD%BF%E7%94%A8%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E4%B8%BB%E6%9C%BA%E5%9C%B0%E5%9D%80%E7%94%9F%E6%88%90%20shellscript%20%E8%8F%9C%E5%8D%95%EF%BC%8C%E5%B9%B6%E5%9C%A8%E6%AF%8F%E4%B8%AA%E9%80%89%E9%A1%B9%E4%B8%8B%E6%96%B9%E6%98%BE%E7%A4%BA%E5%B8%A6%E6%9C%89%E2%80%9Cping%20%E7%8A%B6%E6%80%81%E2%80%9D%E7%9A%84%E9%80%89%E9%A1%B9%EF%BC%9F.png)
问题:使用文件中的主机地址生成 shellscript 菜单,并在每个选项下方显示带有“ping 状态”的选项?你有什么想法可以帮忙吗?
文件名:bssh.sh
#!/bin/bash
# Display Servers
echo "Servers List"
echo ""
SERVERS="servers_list.txt"
while IFS= read -r SERVERS_LINE || [[ -n "$SERVERS_LINE" ]]; do
serveraddress=$(echo $SERVERS_LINE | cut -d"@" -f 2)
servername=$(echo $SERVERS_LINE | cut -d"@" -f 1)
if ping -c 1 -W 1 $serveraddress >/dev/null 2>&1; then
echo -e "$servername [\033[0;32mOnline\033[0m]"
echo ""
else
echo -e "$servername [\033[0;31mOffline\033[0m]"
echo ""
fi
done <"$SERVERS"
readarray -t Servers < servers_list.txt
PS3=$'\n'"Enter your choice or 0 to exit: "
select selection in "${Servers[@]}"; do
if [[ $REPLY == "0" ]]; then
echo -e "\033[0;90mPeace Out!\033[0m" >&2
exit
else
# Modify the way the program is called
if [[ -e /usr/bin/ssh ]]; then
echo ""
ssh "$selection"
#echo ""
else
echo ""
ssh "$selection"
#echo ""
fi
break
fi
done
文件名:servers_list.txt
[email protected]
[email protected]
[email protected]
答案1
首先,您可以readarray
通过读取一次文件来填充数组。无论哪种方式,一旦填充了数组,您就可以简单地重新使用该数组并在使用它从每个条目中提取所需的位时解析它:
$ cat se.sh
#!/bin/bash
readarray ssh_users < input
printf "SSH connections list:\n"
for connection in ${ssh_users[@]}; do
printf "%s\n" "${connection}"
done
printf "Users list:\n"
for user in ${ssh_users[@]}; do
printf "%s\n" "${user%%@*}"
done
printf "Servers list:\n"
for server in ${ssh_users[@]}; do
printf "%s\n" "${server##*@}"
done
$ ./se.sh
SSH connections list:
[email protected]
[email protected]
[email protected]
Users list:
root
validusername
ufo
Servers list:
127.0.0.1
127.0.0.1