0

Ok I need help figuring out why this code doesn't work, I've listed my problem below the code.

#!/bin/bash

if [ "$1" == "" ]
then
        echo "You forgot an IP adress!"
        echo "Syntax: ./ipsweep.sh xxx.xxx.x"

else
        for ip in `seq 1 254`; do
        ping -c 1 $1.$ip | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" &
        done
fi

now when I run the command ./ipsweeper.sh the program still runs even though the input is nothing. Please help can't see where it fails.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

2 Answers2

2

This:

if [ "$1" == "" ]

should be changed to:

if [ -z "$1" ]

-z is true if the string is zero length.

== is used with [[ ]] while = is used with [ ].

You can read more about bash string comparison in How to Compare Strings in Bash.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
0

You can also check for...

pingit(){
ping -c1 ${1}
}

if [ ${#} -gt 0 ]
then
    pingit ${1}
fi

...the number of arguments. Then you can source it without argument or use it with argument...

 # . pingit.sh 
 # pingit localhost
PING localhost(localhost (::1)) 56 data bytes
64 bytes from localhost (::1): icmp_seq=1 ttl=64 time=0.058 ms

--- localhost ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.058/0.058/0.058/0.000 ms
 # sh pingit.sh localhost
PING localhost(localhost (::1)) 56 data bytes
64 bytes from localhost (::1): icmp_seq=1 ttl=64 time=0.031 ms

--- localhost ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.031/0.031/0.031/0.000 ms
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15