Friday, April 27, 2007

How to Run a Bash Command on All Items in a List

For Linux / Unix
Follow as instructed

For Windows
Download cygwin from http://cygwin.com
For instructions, see this article: http://systemnotesorg.blogspot.com/2007/04/use-cygwin-to-run-linux-on-windows.html

Two Easy Steps for One-Liners

e.g., you have a list of servers, and would like to do something, such as ping each one, or check their IP address. Here is a quick two-step process, with a one-line shell script that can be run from the command line.

1) Create a Text file, with one hostname per line
2) Run a for loop on the file

$ cat servers.txt
server01
server02
server03

$ for host in `cat servers.txt`;do host $host;done
server01.example.com has address 10.10.10.10
server02.example.com has address 10.10.10.11
server03.example.com has address 10.10.10.12
$

If you want different output, you can use awk, but that's another topic.

Notice a few things about this one line script.
1) Each command is separated by a semicolon ";"
2) The back ticks around a command and parameter causes the results to be returned
3) The variable host is assigned in the first part, and called just before done

Note: if you want to use ping, try "ping -c 1 $host", or it will never finish.

No comments: