Im writing on a shell script to deploy my master-node. To setup the node I would like to get a choice of available IP addresses the master should later listen on:
PS3='Please select a network the master should listen onto: '
ips=($(hostname -I))
select ip in "${ips[@]}"
do
case $ip in
"Option 1")
echo "you chose choice 1"
;;
"Quit")
break
;;
*) echo "invalid option $REPLY";;
esac
done
But I run into "invalid option". How can I properly select the IP from my list and use it further as variable at my script?
You need to match digits. something like
#!/usr/bin/env bash
PS3='Please select a network the master should listen onto: '
ips=($(hostname -I))
ips=("${ips[@]}" 'Quit')
select ip in "${ips[@]}"; do
case $ip in
*[0-9]*)
echo "you chose choice $REPLY with the value of $ip"
break
;;
Quit) echo quit
break;;
*) echo Invalid option >&2;;
esac
done
How can I properly select the IP from my list and use it further as variable at my script?
This is a generic solution : will work independently of the array content.
select ip in "${ips[@]}" "Quit"; do
if [[ $ip = "Quit" ]]; then
echo "Exiting ..."
exit
elif (( REPLY > ${#ips[@]} + 1 )); then
echo "invalid option $REPLY"
else
break
fi
done
echo "IP: $ip OPTION: $REPLY"
Explanation
The chosen option must not be greater than the number of elements in the IPs array plus the added exiting option.
NOTE : We're adding Quit to select options but not to the array so I will be clean for further use.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.