Writing a Bash For Loop

The power to our lab machines is controlled by a device we built in 2001. It uses the serial port to control a bank of relays. For more information on the device and how to build it, see this article. Now, it turns out that we often need to simply turn on all machines and then turn them all off when we are done. While we had used a TCL/TK Wish interface with buttons for individual machines, it is useful to have a command that turns off every box, or turns them all on. To further complicate things, there needs to be a delay between turning on each relay because of voltage transients. It also gave us a chance to brush up on Bash. Here is a simple script to turn on all of the relays:

[usr-1@srv-1 ~]$ cat allon
#!/bin/bash
for ((i=100;i<=115;i+=1)); do
echo $i
sleep 1
echo $i > /dev/ttyS1
done
[usr-1@srv-1 ~]$

Let’s run the script after making it executable:

[usr-1@srv-1 ~]$ chmod 700 allon
[usr-1@srv-1 ~]$ ./allon
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
[usr-1@srv-1 ~]$

Here is a script to turn them all off again:

[usr-1@srv-1 ~]$ cat alloff
#!/bin/bash
for ((i=200;i<=215;i+=1)); do
echo $i
sleep 1
echo $i > /dev/ttyS1
done
[usr-1@srv-1 ~]$

Let’s make the script executable and run it:

[usr-1@srv-1 ~]$ chmod 700 alloff
[usr-1@srv-1 ~]$ ./alloff
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
[usr-1@srv-1 ~]$