1

I am using a bash script to see if the given processes are running. If they are not running then it prints Process `$p' is not running. However, if ALL processes are running I want it to print: "Processes are running" only once.

But the problem is that it prints out "Processes are running" multiple times and it is printed out even though there are processes which are not running. I think something is wrong with the For Loop.

#!/bin/bash


check_process=( "ssh" "mysql" "python" )

for p in "${check_process[@]}"; do
    if ! pgrep -x  "$p" > /dev/null; then
        echo "Process \`$p' is not running"
    else
        echo "Processes are running"
    fi
done

1 Answer 1

2

Essentially, you want to implement a logical AND condition. You can do that with:

#!/bin/bash


check_process=( "ssh" "mysql" "python" )

allrunning=1
for p in "${check_process[@]}"; do
    if ! pgrep -x  "$p" > /dev/null; then
        echo "Process \`$p' is not running"
        allrunning=0
    fi
done
if [ $allrunning -eq 1 ]
then
      echo "Processes are running"
fi
Sign up to request clarification or add additional context in comments.

2 Comments

It is not printing out "Processes are running" even though the processes from check_process are running, The script just runs and nothing happens.
@markford Sorry, there was a typo, now I think it should work.

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.