Im new to bash scripting.
I need a script to get the ms of a ping to a IP and if the time is over 100 it will print a echo message.
For the example lets do it with the google ip 8.8.8.8
Could you please help me?
Edit:
Okay how to make it like this:
#!/bin/sh
echo '>> Start ping test 2.0'
/bin/ping 8.8.8.8 | awk -F' |=' '$10=="time"'
if [$11>100]
then
echo "Slow response"
else
echo "Fast response"
fi
Okay... First off, you are not writing a bash script, your script is called using #!/bin/sh
, so even if your system uses bash as its system shell, it's being run in sh compatibility mode. So you can't use bashisms. Write your script as I've shown below instead.
So... it seems to me that if you want your ping
to have output that is handled by your script, then the ping
needs to actually EXIT. Your if
will never get processed, because ping
never stops running. And besides $11
within the awk script isn't the same as $11
within the shell script. So something like this might work:
#!/bin/bash
while sleep 5; do
t="$(ping -c 1 8.8.8.8 | sed -ne '/.*time=/{;s///;s/\..*//;p;}')"
if [ "$t" -gt 100 ]; then
# do something
else
# do something else
fi
done
This while loop, in shell (or bash) will run ping every five seconds with only one packet sent (the -c 1
), and parse its output using sed
. The sed
script works like this:
/.*time=/{...}
- look for a line containing the time and run stuff in the curly braces on that line...s///
- substitute the previously found expression (the time) with nothing (erasing it from the line)s/\..*//
- replace everything from the first period to the end of the line with nothing (since shell math only handles integers)p
- and print the remaining data from the line.And alternate way of handling this is to parse ping
's output as a stream instead of spawning a new ping process for each test. For example:
#!/bin/bash
ping -i 60 8.8.8.8 | while read line; do
case "$line" in
*time=*ms)
t=${line#.*=} # strip off everything up to the last equals
t=${t% *} # strip off everything from the last space to the end
if [[ (($t > 100)) ]]; then
# do something
else
# do something else
fi
;;
done
These solutions are a bit problematic in that they fail to report when connectivity goes away ENTIRELY. But perhaps you can adapt them to handle that case too.
Note that these may not be your best solution. If you really want a monitoring system, larger scale things like Nagios, Icinga, Munin, etc, are a good way to go.
For small-scale ping monitoring like this, you might also want to look at fping.