Free Republic
Browse · Search
General/Chat
Topics · Post Article

To: ShadowAce
Loops are awesome and powerful. One really useful thing that you can do in a loop is to test for the existence (or absense) of a file. If the file exists, you can do one thing, if the file doesn't you can do another.

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.

5 posted on 03/05/2019 8:33:58 AM PST by zeugma (Power without accountability is fertilizer for tyranny.)
[ Post Reply | Private Reply | To 1 | View Replies ]


To: zeugma

Syntax error. In the second script the “do” should be “then”. That’s what I get for writing on the fly without testing.


6 posted on 03/05/2019 8:36:52 AM PST by zeugma (Power without accountability is fertilizer for tyranny.)
[ Post Reply | Private Reply | To 5 | View Replies ]

Free Republic
Browse · Search
General/Chat
Topics · Post Article


FreeRepublic, LLC, PO BOX 9771, FRESNO, CA 93794
FreeRepublic.com is powered by software copyright 2000-2008 John Robinson