References

https://github.com/jymcheong/OpenEDR/issues/23

https://stackoverflow.com/a/66342175

Goals

  1. Write a bash shell script to list all IP addresses into an array
  2. Show the addresses as numeric options with a timed (eg. 10 seconds) prompt, see stackoverflow link above
  3. Print the selected address, otherwise default to 127.0.0.1

YJ's Documentation

Aim

Create a shell script to prompt IP address selection during backend installation. This is to do away with modifying .env after installation: https://github.com/jymcheong/OpenEDR/wiki/0.-Installation#modify-env-to-reassign-frontend_ip

Shell Script

Gist link: https://gist.github.com/real-yj98/49f7572e062d910c706f5e6a1a0058c9

How does it work?

  1. Store all IP addresses of the machine into an array.
  2. For each IP address in the array, print out the IP address with its assigned number i.e. index.
  3. Ask user to enter the number that corresponds to the desired IP address.

Codes

#!/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"

References

https://stackoverflow.com/questions/23934425/parse-ifconfig-to-get-only-my-ip-address-using-bash