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.com
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

?


Solution 1:

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.

Solution 2:

Try this:

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

or

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