带数组的选项菜单

Options menu with array

我正在尝试制作一个脚本以从文件中获取 ip 列表并使用 select 选项将其显示在屏幕上,并通过 selecting 将 ssh 连接到该 IP。文件如下;

name1 1.1.1.1 
name2 2.2.2.2
name3 3.3.3.3
name4 4.4.4.4

下面的脚本可以从文件中读取列表并在屏幕上显示为 menu.It 显示 selection 的名称和 IP,但我只想显示 selection 菜单按名字。我怎样才能做到这一点?

PS3='Please enter your choice: '
readarray -t options < ./file.txt

select opt in "${options[@]}"
do
IFS=' ' read name ip <<< $opt
case  $opt  in  
       $opt) ssh $ip;; 

esac
done

1) name1 1.1.1.1
2) name2 2.2.2.2
3) name3 3.3.3.3
4) name4 4.4.4.4
Please enter your choice: 1

我假设这是 bash,而不是 sh。

select 命令不那么常用。你遇到的问题是你用 readarray 将整行输入 $options,而 select 命令没有为你提供格式化或 [=22] 的方法=] 输出。

一种方法是在读取数组后将其拆分:

#!/usr/bin/env bash

declare -a opt_host=()   # Initialize our arrays, to make sure they're empty.
declare -A opt_ip=()     # Note that associative arrays require Bash version 4.
readarray -t options < ./file.txt

for i in "${!options[@]}"; do
  opt_host[$i]="${options[$i]%% *}"             # create an array of just names
  opt_ip[${opt_host[$i]}]="${options[$i]#* }"   # map names to IPs
done

PS3='Please enter your choice (q to quit): '
select host in "${opt_host[@]}"; do
  case "$host" in
    "") break ;;  # This is a fake; any invalid entry makes $host=="", not just "q".
    *) ssh "${opt_ip[$host]}" ;;
  esac
done

您的代码是正确的,但要解决 bash 4.0、4.1 和 4.2 中的错误,您需要在此处的字符串中引用参数扩展。

IFS=' ' read name ip <<< "$opt"