Ubuntu – In Bash, how to read a file and take each line as incremental variable

bashcommand linescripts

I have a file like below: (list.txt)

127.0.0.1 us
127.0.0.2 uk
127.0.0.3 cn
127.0.0.4 fr
127.0.0.5 ru
127.0.0.6 bd
127.0.0.7 hk

I wanted to make an script which will show the user as items to chose.

bash ping.sh
Which ip you want to test?

1) 127.0.0.1-us
2) 127.0.0.2-uk
3) 127.0.0.3-cn
4) 127.0.0.4-fr
5) 127.0.0.5-ru
6) 127.0.0.6-bd
7) 127.0.0.7-hk

Input: 6

ping -c 5 127.0.0.6

That list will change whenever the file changes. How can i do that ?

Best Answer

#!/bin/bash

PS3="Input: "

while read -r addr tld; do
  addrlist+=( "$addr" ) 
done < list.txt

echo "Which ip you want to test?"

select addr in "${addrlist[@]}"; do
  ping -c5 "$addr"
  break;
done

Note that if your file had contained just a single (address) field, you could have use the bash mapfile built-in (or its synonym readarray)

mapfile -t addrlist < list.txt

to fill the array without explicit looping. If you want the exact hyphenated list shown in the original question then you could do something like

mapfile -t addrlist < list.txt

echo "Which ip you want to test?"

select addr in "${addrlist[@]// /-}"; do
  ping -c5 "${addr%%-*}"
  break;
done

but the code starts to get ugly IMHO.