2

I'm working on a script in Linux Bash, with different kinds of options to use. Basically, the program is going to ping to the given ip-address.

Now, I want to enable the user to write a range of ip-adresses in the terminal, which the program then will ping.

Fe: bash pingscript 25 - 125

the script will then ping all the addresses between 192.168.1.25 and 192.168.1.125.

That's not to hard, I just need to write a little case with

[0-9]-[0-9] ) ping (rest of code)

Now the problem is: this piece of code will only enable me to ping numbers of fe. 0 - 9 and not 10 - 25.

For that I'd need to write: [0-9][0-9]-[0-9][0-9] (fe: ping 25 - 50)

But then there's the possibility of having 1 number on one side and 2 on the other: [0-9]-[0-9][0-9] (fe: ping 1 - 25)

or: [0-9]-[0-9][0-9][0-9] (fe: ping 1 - 125)

and so on... That means there're a lot of possibilities. There's probably another way to write it, but how?

I don't want any letters to be in the arguments, but I can't start with that (loop-through system).

Kryptonous
  • 99
  • 1
  • 2
  • 11

2 Answers2

3

How about that:

for i in 192.168.1.{25..125}; do ping -qnc1 $i; done

Or in a script with variables as arguments:

for i in $(seq -f "192.168.1.%g" $1 $2); do ping -qnc1 -W1 $i; done

Where the first argument is the number where to begin and the second argument where to end. Call the script like this:

./script 25 125

The ping options:

  • -q: that ping doesn't print a summary
  • -n: no dns lookups
  • -c1: Only send 1 package
  • -W1: timeout to 1 second (can be increased of cource)
chaos
  • 8,162
  • 3
  • 33
  • 40
  • Would you mind to explain the options/functions used in your second piece of code? I don't really get the `-qnc1 -W1 $i` and the `$(seq -f (...).%g` . – Kryptonous May 26 '15 at 12:32
  • Thanks, and what does the `$(seq -f ` mean? Or do you have a link to its explanation? Many thanks, already! – Kryptonous May 26 '15 at 12:54
  • 1
    @Kryptonous `seq 25 125` for example prints just all numbers from 25 to 125. `-f` is the format that this output should have. In your case: 192.168.1.25 to 192.168.1.125 if $1 is 25 ans $2 is 125. – chaos May 26 '15 at 15:19
2

You can use extended pattern matching in your script by enabling the extglob shell option:

shopt -s extglob

So you can use braces with a + quantifier like this:

#!/bin/bash

shopt -s extglob

case $1 in
+([0-9])-+([0-9]) )
    # do stuff
    ;;
esac
Forketyfork
  • 7,416
  • 1
  • 26
  • 33
  • Can this also be used in bash? As I see that you use `#!/bin/sh` ? – Kryptonous May 26 '15 at 12:48
  • 1
    @Kryptonous yes, it can be used in bash, here's the docs http://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html I've corrected my answer. – Forketyfork May 26 '15 at 12:52
  • I tried it in bash, and it works indeed. Thanks for the link! This really helped. The good thing is I can implement both solutions to achieve the desired output. – Kryptonous May 26 '15 at 12:55