Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write if else in one line in shell?

I would like to write in one line this:

if [$SERVICESTATEID$ -eq 2]; then echo "CRITICAL"; else echo "OK"; fi

So to do a test in my shell I did:

if [2 -eq 3]; then echo "CRITICAL"; else echo "OK"; fi

The result is

-bash: [2: command not found
OK

So it doesn't work.

like image 472
user6066403 Avatar asked Jun 08 '16 08:06

user6066403


People also ask

How do you write an if statement in one line in bash?

The syntax of an bash if statement A short explanation of the example: first we check if the file somefile is readable (“if [ -r somefile ]”). If so, we read it into a variable. If not, we check if it actually exists (“elif [ -f somefile ]”).

How do you write if-else in shell?

If specified condition is not true in if part then else part will be execute. To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.

What does if [- Z mean in shell?

The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something. NOTE: The -z flag doesn't directly have anything to do with the "if" statement. The if statement is used to check the value returned by test. The -z flag is part of the "test" command.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.


1 Answers

Space -- the final frontier. This works:

if [ $SERVICESTATEID -eq 2 ]; then echo "CRITICAL"; else echo "OK"; fi

Note spaces after [ and before ] -- [ is a command name! And I removed an extra $ at the end of $SERVICESTATEID.

An alternative is to spell out test. Then you don't need the final ], which is what I prefer:

if test $SERVICESTATEID -eq 2; then echo "CRITICAL"; else echo "OK"; fi
like image 146
Jens Avatar answered Sep 17 '22 17:09

Jens