Bash - if statement combined with mail command

bash, email, if-statement, linux

Solution

I need to write a 1 liner which will ping a server and will send an email when there's no response.

You seem to have complicated things. Simply check for the `ping` status:

subject="Host_down";
if ! ping -c1 -w3 100.100.100.100; then
  mail -s $subject admin@example.com < file.txt;
fi

The `mail` command would be executed if `ping` returns with a non-zero exit code.

EDIT: As noted by chepner, a double-quoted string preceded by a dollar-sign (`$`) would cause the string to be translated according to the current locale. So you probably wanted to say:

subject="Host_down"

instead of saying

subject=$"Host_down"

Problem

I need to write a 1 liner which will ping a server and will send an email when there's no response. I wrote this so far ``` subject=$"Host_down" ; i=$(ping -c1 -w3 100.100.100.100 | grep 100%) ; j=$(echo $i | wc -l) ; if [ $j -eq 1 ] ; then mail -s $subject admin@example.com < file.txt ; fi ``` but it sends email in both cases when if statement is either true or false. When I put "echo $i" instead of "mail..." like that ``` subject=$"Host_down" ; i=$(ping -c1 -w3 100.100.100.100 | grep 100%) ; j=$(echo $i | wc -l) ; if [ $j -eq 1 ] ; then echo $i ; fi ``` then the if statement works fine and outputs $i when the server is down only. I tried this as well ``` subject=$"Host_down" ; i=$(ping -c1 -w3 100.100.100.100 | grep 100%) ; j=$(echo $i | wc -l) ; if [ $j -eq 1 ] ; then echo $i | mail -s $subject admin@example.com ; fi ``` and in this case also emails are sent when if gives true or false. I know programming a bit but I'm beginner in bash. Any advice on what I am doing wrong will be highly appreciated.

Original source