-
-
Save real-yj98/49f7572e062d910c706f5e6a1a0058c9 to your computer and use it in GitHub Desktop.
Prompt IP address selection with 10 seconds timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Store all IP addresses of the machine into an array | |
mapfile -t ipArray < <(ip a | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print $2}') | |
# List out the IP addresses stored in the array | |
echo "List of IP addresses" | |
for key in "${!ipArray[@]}" | |
do | |
echo "$key: ${ipArray[$key]}" | |
done | |
# Set FRONTEND_IP to default 127.0.0.1 | |
FRONTEND_IP=127.0.0.1 | |
# Ask user to enter the desired IP address | |
read -t 10 -p "Select the IP address that you wish to use e.g. 1: " option | |
# If user does not enter within 10 seconds, set FRONTEND_IP to default 127.0.0.1 | |
if [[ $? -gt 128 ]] ; then | |
echo -e "\nTimeout. Setting IP address to default 127.0.0.1..." | |
else | |
# Check if input only contain numbers | |
if ! [[ "$option" =~ [^[:digit:]]+ ]] ; then | |
# If user enters without any input, set FRONTEND_IP to default 127.0.0.1 | |
if [[ $option = "" ]]; then | |
echo "No input entered. Setting IP address to default 127.0.0.1..." | |
# If user entered a valid number from the list, set FRONTEND_IP to the selected IP address | |
elif [[ -v "ipArray[option]" ]] ; then | |
echo "Valid number selected. Setting IP address to ${ipArray[option]}..." | |
FRONTEND_IP=${ipArray[option]} | |
# If user entered a number not from the list, it is an invalid number. Set FRONTEND_IP to default 127.0.0.1 | |
else | |
echo "Invalid number selected. Setting IP address to default 127.0.0.1..." | |
fi | |
#If input does not contain only numbers, it is an invalid input. Set FRONTEND_IP to default 127.0.0.1 | |
else | |
echo "Invalid input. Setting IP address to default 127.0.0.1..." | |
fi | |
fi | |
# Print the selected IP address | |
echo "Selected IP address = $FRONTEND_IP" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment