MLUG Bash Scripting Workshop 25/04/08 | ||
---|---|---|
Prev | Index | Next |
I figured the easiest way easiest way to see if someone is up is to ping them. I had a couple tries came up with the following little test script which would tell me whether anyone was home at the target IP.
I will provide all my explanations as comments in the example03 script. Go ahead and have a play with it or the alternative and totally redundant example03a.
#!/bin/bash # example03 # Manually edit this variable declaration to test script IP1=192.168.1.24 ping -c1 $IP1 > /dev/null 2>&1 # Ping will return a zero if there was a packet returned # from the target IP if [ $? -eq 0 ];then echo "ping returned" else echo "no ping returned" fi # "> /dev/null" redirects standard out (stdout) to /dev/null # "which is where things go to dissappear on nix systems" # "2>&1" redirects standard error (stderr) to stdout so that # "they both go down the drain. In short there is no output # from ping with the exception of 0 or 1 to the system at exit.
However, in order to use this test in a script on a server where nobody is around to see what prints to standard out, I needed to change the if statement to produce a variable I could pass on. I decided on using a value of 2 if a packet was returned to ping and a 1 if there was no packet returned. This was totally arbitrary on my part.
ping -c1 $IP1 > /dev/null 2>&1 if [ $? -eq 0 ];then TEST1=2 else TEST1=1 fi
Hint! Hint !: If you ever want to grab the actual exit number use a construct such as this:
ping -c1 192.168.1.1 > /dev/null 2>&1 exit_no=$? echo "$exit_no"
You can use it with any command that exits with a number.