0

I am trying to use an IF statement to:

  1. Check if a server is UP
  2. Check if a file exists on the server

My Code So Far

hostname="somehost.com"
file="somefile.txt"
URL="https://${hostname}/some/directory/${file}"
if [ "ping -c 1 -W 1 ${hostname} 2>/dev/null" ] & [ "wget --spider ${URL} 2>/dev/null" ];
then
echo -e "${hostname} is UP and ${file} is AVAILABLE"
else
echo -e "${hostname} is DOWN or ${file} is UNAVAILABLE"
fi

I have tried testing the IF statement by entering an incorrect hostname and an incorrect file but, the result is incorrect.

Current Output

somehost.com is UP and somefile.txt is AVAILABLE

Expected Output

somehost.com is DOWN and somefile.txt is DOWN
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
arnpry
  • 1,103
  • 1
  • 10
  • 26
  • 1
    Remove both the square brackets (those're for testing *expressions*, not commands; see ["Bash conditional based on exit code of command"](https://stackoverflow.com/questions/49849957/bash-conditional-based-on-exit-code-of-command/49850110)) and the double-quotes around the commands (those make them plain strings rather than commands). Also, don't use `echo -e` -- the `-e` is just a compatibility trap waiting to cause trouble. – Gordon Davisson Apr 07 '22 at 17:38
  • 1
    And use `&&` to make AND of both checks – Romeo Ninov Apr 07 '22 at 19:31
  • Thanks everyone! Neither of those suggestions are producing the expected output unfortunately – arnpry Apr 08 '22 at 09:50
  • @arnpry Please update your question with the current code. – Gordon Davisson Apr 10 '22 at 01:28
  • @arnpry, if you don't show us _how_ you followed the instructions, we can't say why following them didn't fix things. – Charles Duffy Apr 11 '22 at 00:09
  • 1
    @arnpry, ...btw, as a rule, it's always a good habit to run code through http://shellcheck.net/ and fix what it identifies before asking questions here. I'd suggest doing that after updating your code per the two linked questions' answers, before editing or reposting this question. – Charles Duffy Apr 11 '22 at 00:11

1 Answers1

1
expression1 && expression2

True if both expression1 and expression2 are true.

expression1 || expression2

True if either expression1 or expression2 is true.

The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.

From: https://www.gnu.org/software/bash/manual/bash.html#Compound-Commands

Nic3500
  • 8,144
  • 10
  • 29
  • 40