Search code examples
linuxbashscriptingautomationsuse

My first Bash script does not look so efficient


This is my first bash script using some resources I found online. I think there is a better way to write this perhaps using some other form of conditionals (if then vs control operators).

It is a script that basically checks if a host is up or down (check if it is ping-able). You dump all the ip addresses you want into a file, then run the script calling on the file. The text file looks like this:

8.8.8.8                                                                                                             
4.8.8.8                                                                                                             
4.4.4.4                                                                                                             
127.0.0.1

The actual script looks like this. Is the 2>&1 necessary because it worked without. I had to play around with the brackets a lot.

#!/bin/bash                                                                                                         

while read line                                                                                                     
do                                                                                                                  
A=$(ping -c 1 $line)                                                                                                
((echo $A | grep "64 bytes") > /dev/null 2>&1 && (echo "UP - "$line)) || echo "DOWN - "$line                        
done < $1 

Thank you!


Solution

  • You can do it entirely without brackets:

    while read -r address; do
      ping -c 1 $address >/dev/null 2>&1 && echo "UP - $address" || echo "DOWN - $address"
    done < file
    

    The >/dev/null 2>&1 redirects both STDOUT and STDERR to /dev/null meaning that whatever ping outputs won't be printed to your terminal.

    You can then use the && and || operators to echo a message in case of success (ping exits with 0) or failure (ping exits with >0)

    You could use if..then..else if you prefer:

    while read -r address; do
      if ping -c 1 $address > /dev/null 2>&1; then 
        echo "UP - $address"
      else 
        echo "DOWN - $address"
      fi
    done < file