Home > Net >  PING multiple Arguments with BASH script
PING multiple Arguments with BASH script

Time:03-23

I try to do a simple script with BASH that try to ping each Arguments($1 $2 $3...etc). From now, I'm able to ping a single argument and receive the good answer but it not working properly with multiple arguments entered; like this (./Script.sh Arg1 Arg2....). Plus, the script work for a single Arguments entry but it keeps telling me that their is an error link to my line 6 just before giving the echo link to the condition.

#!/bin/bash


PING=`ping -c 1 "$@" | grep bytes | wc -l` 

for input in "$@"; do "${PING}" ;
    if [[ "$PING" -gt 1 ]];then 
        echo "L'address IP ping"
    else
        echo "L'adresse IP ne ping pas"
    fi
done

and the output is :

./bash3.sh: line 6: 2: command not found
L'address IP ping

if I add more then one address before executing it always pass by the else which is "Address unreachable"

CodePudding user response:

You're setting PING to the output of the ping -c 1 "$@" | grep bytes | wc -l command when the script starts. You're not setting it to the command line so that you can execute it during the loop.

Use a function, not a variable.

You can also use the -c option to grep to return the count of matches, rather than piping to wc -l

ping_count() {
    ping -c 1 "$@" | grep -c bytes
}

for ip in "$@"; do
    if [[ $(ping_count "$ip") -gt 1 ]];
    then echo "L'address $ip ping"
    else echo "L'adresse $ip ne ping pas"
    fi
done

Also, ping sets its exit status based on whether it got a response. So instead of counting matching lines, just test the result of ping.

for ip in "$@"; do
    if ping -c 1 -q "$ip"
    then echo "L'address $ip ping"
    else echo "L'adresse $ip ne ping pas"
    fi
done

CodePudding user response:

#!/usr/bin/env bash

for input in "$@" 

    do  
        ping=$(ping -c 1 $@ | grep bytes | wc -l)
        if [ $ping -gt 1 ];  then 
            echo "L'address IP ping"
        else
            echo "L'adresse IP ne ping pas"
        fi  
    done
  • Related