bash - Options menu with array -
i trying make script ip list file , show on screen select option, , make ssh ip selecting. file below;
name1 1.1.1.1 name2 2.2.2.2 name3 3.3.3.3 name4 4.4.4.4
below script can read list file , shows on screen menu.it show both name , ips selection, want show selection menu name. how can achieve this?
ps3='please enter choice: ' readarray -t options < ./file.txt select opt in "${options[@]}" 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 choice: 1
i'm assuming bash, not sh.
the select
command isn't used. problem you're having you're slurping whole lines in $options
readarray
, , select
command doesn't provide way format or trim output.
one approach split array after reading it:
#!/usr/bin/env bash declare -a opt_host=() # initialize our arrays, make sure they're empty. declare -a opt_ip=() # note associative arrays require bash version 4. readarray -t options < ./file.txt in "${!options[@]}"; opt_host[$i]="${options[$i]%% *}" # create array of names opt_ip[${opt_host[$i]}]="${options[$i]#* }" # map names ips done ps3='please enter choice (q quit): ' select host in "${opt_host[@]}"; case "$host" in "") break ;; # fake; invalid entry makes $host=="", not "q". *) ssh "${opt_ip[$host]}" ;; esac done
Comments
Post a Comment