Here we go!
- As we are checking whether a host is up or not, we need to take input from the user which will be the target host that the user wants to test if it is up or not. We would need a variable to store the name of this target host, say it will be '$target'.
- So, we have the host to be tested in a variable called '$target'. Now the main part of our logic. We will send an ICMP packet to the target host and we will receive ICMP reply from the host if it is alive and we would save the number of such replies received in a variable, say '$count'. If we get any reply from the target host, we will print "Yes! Host is Alive!", else "Host is not Alive! Try Again Later..".
- To dispatch one ICMP packet to the target host, we would be using 'ping' command with option -c which specifies number of ICMP packets to be sent to the target.
- We will then pipe the output of 'ping command' to the 'grep command' that would display the word starting from 'icmp'.
- Again, we pipe the output of grep to 'wc command' which when used with option -l counts the number of lines. And this count will be stored in the'$count' variable.
- If '$count' is greater than zero, it will denote that we have received an icmp reply from the target host, indicating that the target host is active. And we'll echo 'Yes! Host is Alive!' message on the screen.
- On the other hand, if target host doesn't respond, the $count value will be set as zero indicating that the target host is down. In this case, we will display 'Host is not Alive! Try again later..' message on the screen.
That's it! So simple it is! Now, have a look on the script.
#!/bin/bash target=$1 count=$( ping -c 1 $target | grep icmp* | wc -l ) if [ $count -eq 0 ] then echo "Host is not Alive! Try again later.." else echo "Yes! Host is Alive!" fi