Loops are bad
Loops are a pain
Loops make you do things
again and again
... sorry wrong type of bash
An imminently practical function. One habitual task I use it for is to mute system sound on my PC for a prescribed period of time. Very handy when listening to streaming talk radio because they all seem to only be able to sell ads for men’s virility pills and ambulance-chasing lawyers, which I choose not to listen to.
At invocation, the script mutes the master system sound volume, then asks me how long I want to mute it for. Then it uses a while/if loop of the “sleep” function to count down that many seconds before un-muting.
I wrote similar batch file for Windows using if/then looping. It’s such a relief not to have to listen to that moronic woman teach me how to spell the name of her dog food.
In the following the script checks for the file /tmp/i_exist. If it is there, it sleeps a bit and checks again. Once the file is deleted, it exits. You can use this as a poor man's job control. Let's say you have a job that kicks off every day and does some work. Let's also say that you have a separate job that needs to run, but it is dependent upon the first job finishing successfully before it can run. You can have the first job create a check file, and delete it when it finishes, which will allow the 2nd to execute.
$ cat loopers #!/bin/bash while [ -f /tmp/i_exist ] do echo "It exists" sleep 5 done echo "It no longer exists. Exiting" exit 0 $ ./loopers It exists It exists It exists It exists It no longer exists. Exiting $
Another use for something like this is to test to see if a job is already running. You could have the script create a run file. If the job is running it exists. If you start the same job a second time, it could see that the file already exists, and refuse to run. There are other possible ways to do this as well, but this is quick and dirty, and generally works, as long as the job completes successfully and cleans up after itself. If the script is killed while executing, it might not do so, so subsequent executions will see the file and thus refuse to run.
$ cat loopers #!/bin/bash if [ -f /tmp/i_exist ] do echo "Check file exists! Check to see if another copy of this program is running." exit 1 done echo "Now I can create the file" touch /tmp/i_exist echo "Real work would be done here, since the file didn't exist." echo "Now I clean up after myself..." rm /tmp/i_exist exit 0
Note that above I used "if" instead of 'while'. Either would work in this instance.