1

I have a command in a variable in Bash:

check_ifrunning=\`ps aux | grep "programmname" | grep -v "grep" | wc -l\`

The command checks if a specific program is running at the moment. Later in my script, I want to query the value of the variable on a point. If the specific program is running, the script should sleep for 15 minutes.

I solved it like this:

while [ $check_ifrunning -eq 1 ]; do
sleep 300
done

Will the script execute the command in the variable for each single loop-run or will the value in the variable stay after the first execution?

I have more variables in my script which can change their value. This was just one simple example of this.

2 Answers 2

1

Notice that check_ifrunning is set only once, in

 check_ifrunning=`ps aux | grep "programmname" | grep -v "grep" | wc -l`

and that it is set before the loop:

 while [ $check_ifrunning -eq 1 ]; do
   sleep 300
 done

You could add, for debugging purposes, an echo check_ifrunning is $check_ifrunning statement inside your while loop just before the sleep ...

You probably simply want (using pidof(8)) - without defining or using any check_ifrunning Bash variable:

 while [ -n "$(pidof programname)" ]; do
    sleep 300
 done

Because you want to test if programname is running at every start of the loop!

You should use the more nestable and more readable $(...) instead of backquotes.

Consider reading the Advanced Bash Scripting Guide...

If you are writing a Bash script, consider to start it with

 #!/bin/bash -vx

while debugging. When you are satisfied, remove the -vx...

Sign up to request clarification or add additional context in comments.

2 Comments

First of all thank you for answer. So I have to "re-set" the varibale everytime before a loop? Would this be possible with a function, which I call before every loop? As already mentioned, I have more variables like these in my script. They may change during the run of the script.
Read more about bash scripting. Use the -vx trick. You seems very confused about what variables are in bash....
1

If you want to encapsulate your commands, the proper way to do that is a function.

running () {
    ps aux | grep "$1" | grep -q -v grep
}

With grep -q you get the result as the exit code, not as output; you use it simply like

if running "$programname"; then
    :

Ideally, the second grep is unnecessary, but I did not want to complicate the code too much. It still won't work correctly if you are looking for grep. The proper solution is pidof.

See also http://mywiki.wooledge.org/BashFAQ/050

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.