Bash - if statement combined with mail command

I need to write 1 liner that will ping the server and send an email when there is no reply. I wrote it 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 an email in both cases if the if statement is either true or false. When I put "echo $ i" instead of "mail ..." like this

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 issues $ i when the server is just down.

I tried it too

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

in which case emails are also sent if they return true or false. I know a little programming, but new to bash. Any advice on what I am doing wrong will be greatly appreciated.

+4
source share
2

1 , .

, , . ping:

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

mail , ping .


EDIT: chepner, , ($) , . , , :

subject="Host_down"

,

subject=$"Host_down"
+4

:

j=$(echo $i | wc -l) ;

:

j=$(echo -n $i | wc -l) ;

-n , echo , $i . , wc -l 0, 1.

"" , : " if $i, ", , : .

+1

Source: https://habr.com/ru/post/1527094/


All Articles