0

I want to retrieve all connected hosts with a script:

for i in {1..9}
do 
    ping -c 1 -w 1 8.8.8.$i | grep ' 0%'
done

So i want to add a condition using if, which would test if the output of each ping (with the piped grep) is empty or not, if it's not empty then host is up.

Cheers

p.s: i would like to avoid the use of a file

aurelien75000
  • 25
  • 1
  • 9

5 Answers5

1

Using the ping return code to determine the status of the machine.

for i in {1..9}
do
    ping_status=$(ping -c 1 8.8.8.$i &> /dev/null && echo success || echo fail)

    if [ $ping_status = success ]
    then echo 'machine is up and running'
    else
       echo 'machine is down'
    fi
done
Inian
  • 80,270
  • 14
  • 142
  • 161
1

Just check the status of the ping command:

for i in {1..9}
do 
    if ping -c 1 -w 1 8.8.8.$i >/dev/null; then 
        echo "$i alive"; 
    else 
        echo "$i dead"
    fi
done
oliv
  • 12,690
  • 25
  • 45
0

How to set a variable to the output from a command in Bash?

for i in {1..9}
do
    out="$(ping -c 1 -w 1 8.8.8.$i | grep ' 0%')"
    if [ -z "$out" ]; then
        # output empty
    fi
done
Community
  • 1
  • 1
0

You could use glob matching within a case/esac. This avoids an expensive fork to grep.

for i in {1..9}; do
   case $(ping -c 1 8.8.8.$i) in
   (*" 0%"*)
      echo something
   ;;
   (*)
      echo something else
   ;;
   esac
done
Jens
  • 69,818
  • 15
  • 125
  • 179
0

You can do it faster in parallel with GNU Parallel like this:

parallel -j 64 -k 'ip=8.8.8.{}; ping -c 1 -t 1 $ip >/dev/null 2>&1; [ $? -eq 0 ] && echo $ip' ::: {1..254}

Or you can use nmap like this:

nmap -sP 8.8.8.* | tr -d "()" | awk '/Nmap scan report/{h=$NF} /Host is up/{print h}'
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432