Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An "and" operator for an "if" statement in Bash

I'm trying to create a simple Bash script to check if the website is down and for some reason the "and" operator doesn't work:

#!/usr/bin/env bash

WEBSITE=domain.example
SUBJECT="$WEBSITE DOWN!"
EMAILID="[email protected]"
STATUS=$(curl -sI $WEBSITE | awk '/HTTP\/1.1/ { print $2 }')
STRING=$(curl -s $WEBSITE | grep -o "string_to_search")
VALUE="string_to_search"

if [ $STATUS -ne 200 ] && [[ "$STRING" != "$VALUE" ]]; then
    echo "Website: $WEBSITE is down, status code: '$STATUS' - $(date)" | mail -s "$SUBJECT" $EMAILID
fi

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

Could you also please advise when to use:

  • single and double square brackets
  • parenthesis

?

like image 434
HTF Avatar asked Nov 16 '12 00:11

HTF


People also ask

Can you use && in an if statement?

In the logical AND ( && ) operator, if both conditions are true , then the if block will be executed. If one or both of the conditions are false , then the else block will be executed.

What is and operator in bash?

Bash AND Logical Operator Bash boolean AND operator takes two operands and returns true if both the operands are true, else it returns false.

What is && and || in shell script?

The operators "&&" and "||" shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output: $ false && echo foo || echo bar $ true || echo foo && echo bar.

What does && mean in Linux?

Logical AND operator(&&): The second command will only execute if the first command has executed successfully i.e, its exit status is zero. This operator can be used to check if the first command has been successfully executed. This is one of the most used commands in the command line.


2 Answers

What you have should work, unless ${STATUS} is empty. It would probably be better to do:

if ! [ "${STATUS}" -eq 200 ] 2> /dev/null && [ "${STRING}" != "${VALUE}" ]; then

or

if [ "${STATUS}" != 200 ] && [ "${STRING}" != "${VALUE}" ]; then

It's hard to say, since you haven't shown us exactly what is going wrong with your script.

Personal opinion: never use [[. It suppresses important error messages and is not portable to different shells.

like image 171
William Pursell Avatar answered Oct 05 '22 15:10

William Pursell


Try this:

if [ "${STATUS}" -ne 100 -a "${STRING}" = "${VALUE}" ]

or

if [ "${STATUS}" -ne 100 ] && [ "${STRING}" = "${VALUE}" ]
like image 32
AnshBikram Avatar answered Oct 05 '22 17:10

AnshBikram