while do read done in one line

This is a simple but useful loop to process an input file if none can be provide with a command option for a certain program. E.g. use every IP address in a file
To be used in bash when you don’t want to write a script just yet.

guru@home:~/utils$ while read -r LINE; do echo "$LINE";sleep 1; done < targethosts.txt
172.16.1.254
172.16.3.11
172.16.3.41
172.16.3.51
172.16.3.61
172.16.3.71
172.16.3.111
172.16.3.253
172.16.4.74
172.16.4.79
172.16.4.80
172.16.4.155
172.16.4.254
172.16.4.76
172.16.4.76
172.16.4.91

Instead of an ordinary echo you would of course use another command.

E.g. a simple ping to each host

guru@home:~/utils$ while read -r LINE; do ping -c2 "$LINE"; done < targethosts.txt
PING 172.16.1.254 (172.16.1.254) 56(84) bytes of data.
64 bytes from 172.16.1.254: icmp_seq=1 ttl=64 time=0.612 ms
64 bytes from 172.16.1.254: icmp_seq=2 ttl=64 time=0.516 ms

--- 172.16.1.254 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1009ms
rtt min/avg/max/mdev = 0.516/0.564/0.612/0.048 ms
PING 172.16.3.11 (172.16.3.11) 56(84) bytes of data.
64 bytes from 172.16.3.11: icmp_seq=1 ttl=127 time=1.50 ms
64 bytes from 172.16.3.11: icmp_seq=2 ttl=127 time=1.39 ms

--- 172.16.3.11 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 1.392/1.446/1.501/0.066 ms
PING 172.16.3.41 (172.16.3.41) 56(84) bytes of data.
64 bytes from 172.16.3.41: icmp_seq=1 ttl=127 time=1.06 ms
64 bytes from 172.16.3.41: icmp_seq=2 ttl=127 time=1.23 ms


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s