command-line for loops

Once you have your ssh keys set up and ssh-agent running, then you can use for loops to execute a command on multiple machines:

SPINACH[~]$ for i in wasabi cucumber sage
more> do
more> echo $i
more> ssh $i uptime
more> echo "-------------------"
more> done
wasabi
 13:32:42 up 3 days, 14:44,  1 user,  load average: 0.00, 0.01, 0.05
-------------------
cucumber
ssh: connect to host cucumber port 22: No route to host
-------------------
sage
 13:32:45 up 97 days,  4:35,  2 users,  load average: 0.03, 0.04, 0.05
-------------------

Using the UP arrow key, you can easily edit your previous command. The for loop commands are all stored as one command!

SPINACH[~]$ for i in wasabi perilla sage; do echo $i; ssh $i uptime; echo "-------------------"; done
wasabi
 13:33:10 up 3 days, 14:44,  1 user,  load average: 0.00, 0.01, 0.05
-------------------
perilla
 13:33:10 up 3 days, 14:44,  0 users,  load average: 0.05, 0.04, 0.05
-------------------
sage
 13:33:10 up 97 days,  4:35,  2 users,  load average: 0.02, 0.04, 0.05
-------------------


You can use backticks to execute any command, and use that command's output as part of your for loop:

SPINACH[~]$ seq 6 9
6
7
8
9


SPINACH[~]$ for i in `seq 6 9`
more> do
more> cal $i 2012
more> done
     June 2012        
Su Mo Tu We Th Fr Sa  
                1  2  
 3  4  5  6  7  8  9  
10 11 12 13 14 15 16  
17 18 19 20 21 22 23  
24 25 26 27 28 29 30  
                      
     July 2012        
Su Mo Tu We Th Fr Sa  
 1  2  3  4  5  6  7  
 8  9 10 11 12 13 14  
...
...

Now combine that with the lists we keep of machine names in each lab:

SPINACH[~]$ for i in `cat /usr/swat/db/hosts.overflow `
more> do
more> echo $i
more> ssh $i uptime
more> done
cheese
 13:38:43 up 3 days, 14:50,  0 users,  load average: 0.00, 0.01, 0.05
dill
ssh: connect to host dill port 22: Connection refused
clove
 13:38:43 up 3 days, 14:50,  0 users,  load average: 0.00, 0.01, 0.05
...
...