Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: If/Else statement in one line

Tags:

bash

People also ask

Can you do else if in bash?

Bash allows you to nest if statements within if statements. You can place multiple if statements inside another if statement.

What does =~ mean in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.

What is && in bash?

The Bash logical (&&) operator is one of the most useful commands that can be used in multiple ways, like you can use in the conditional statement or execute multiple commands simultaneously.


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

&& 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).


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

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

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

more oneliners here