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.
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 ]”).
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.
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.
$? 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With