Conditional execution in bash

For some reason, I needed to run a program, but not if another program is running (can be the same program).

After googling for a bash tutorial, I was able to create the script:

ps aux > psinfo
cat psinfo | grep FORBIDDEN_PROGRAM > programinfo

if [ `wc -l < programinfo` = "0" ]
then
	PROGRAM_TO_RUN
fi

ps is used to list all processes running on the system. grep is used to display all occurences of the string FORBIDDEN_PROGRAM from the output of ps. The output of ps isn’t directly piped to grep, e.g “ps aux | grep FORBIDDEN_PROGRAM” because of the unpredictable behaviour of piping. Sometimes “grep FORBIDDEN_PROGRAM” is started before ps, making 1 entry of the string FORBIDDEN_PROGRAM in the output of ps if FORBIDDEN_PROGRAM is not running. However, sometimes grep is started after ps, which gives a count of 0 if FORBIDDEN_PROGRAM is not running.

wc is used to count the number of lines in a file (and is able to count other things too).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s


%d bloggers like this: