arimbun
arimbun

Reputation: 3915

How to run one command if a previous command succeeds, otherwise run another command

I am trying to check if a process (assume it is called some_process) is running on a server. If it is, then echo 1, otherwise echo 0.

This is the command that I am using but it only works partially (more info below). Note that I need to write the script in one line.

ps aux | grep some_proces[s] > /tmp/test.txt && if [ $? -eq 0 ]; then echo 1; else echo 0; fi

Note: The [s] in some_proces[s] is to prevent grep from returning itself.

If some_process is running, then "1" gets echoed, which is fine. However, if some_process is not running, nothing gets echoed.

Upvotes: 313

Views: 631979

Answers (6)

checkdb: image: mysql:8.0.31 environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_DATABASE: ${MYSQL_DATABASE}

entrypoint: sh -c  'while true; do 
                mysql -h ${DB_MYSQL:-db} --user=${MYSQL_USER:-root} --password=${MYSQL_ROOT_PASSWORD} --execute "use ${MYSQL_DATABASE};";
                if [ $? -eq 0 ]; then exit 0; fi; 
                sleep 5;
              done'

Upvotes: 0

once
once

Reputation: 1399

pgrep -q some_process && echo 1 || echo 0

more oneliners here

Upvotes: 11

William Pursell
William Pursell

Reputation: 212634

There is no need to explicitly check $?. Just do:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0 

Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

Upvotes: 418

John Gilmer
John Gilmer

Reputation: 874

Use grep -vc to ignore grep in the ps output and count the lines simultaneously.

if [[ $(ps aux | grep process | grep -vc grep)  > 0 ]] ; then echo 1; else echo 0 ; fi

Upvotes: 67

Costi Ciudatu
Costi Ciudatu

Reputation: 38265

You can make full use of the && and || operators like this:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0

For excluding grep itself, you could also do something like:

ps aux | grep some_proces | grep -vw grep > /tmp/test.txt && echo 1 || echo 0

Upvotes: 19

ruakh
ruakh

Reputation: 183584

&& means "and if successful"; by placing your if statement on the right-hand side of it, you ensure that it will only run if grep returns 0. To fix it, use ; instead:

ps aux | grep some_proces[s] > /tmp/test.txt ; if [ $? -eq 0 ]; then echo 1; else echo 0; fi

(or just use a line-break).

Upvotes: 92

Related Questions