0

I'm trying to make a ping sweep using bash:

#!/bin/bash

for x in seq 74 254
do
  ping -w 4 192.168.1.$x
done

According to what I've read on the Internet this should be looping from 74 to 254 but outputs only results from 74 and 254.

What am I doing wrong ?

road_runner
  • 459
  • 1
  • 5
  • 15

2 Answers2

1

Best practice is a C-style for loop:

#!/bin/bash

for (( x=74; x<=254; x++)); do
  ping -w 4 "192.168.1.$x"
done
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • or use bash-ism: ```for x in {74..254}``` – vgersh99 Oct 28 '20 at 17:11
  • @vgersh99, you should add your solution as an answer. – Amessihel Oct 28 '20 at 17:13
  • @Amessihel after reading [this](https://stackoverflow.com/questions/19432753/brace-expansion-with-variable), I'd rather leave it as a comment - thanks. – vgersh99 Oct 28 '20 at 17:20
  • 3
    @vgersh99, ...the other thing about that bashism is that it eats all the memory to generate a list before it actually runs any of the items in the list. The C-style `for` loop suggested in this answer doesn't precalculate the numbers -- it generates them only as they're needed. Hardly matters for this short little list, but it could make a difference for a big one. – Charles Duffy Oct 28 '20 at 17:33
0

You forgot to surround the seq call with a "dollar parenthesis" set.

for x in $(seq 74 254)
do
  ping -w 4 192.168.1.$x
done

If you don't do that, seq 74 254 will be parsed a list of values. This is called command substitution. According to the manual page of bash:

Command substitution allows the output of a command to replace the command name. Bash performs the expansion by executing [the] command and replacing the command substitution with the standard output of the command.

Note: Charles Duffy's answer is better.

Amessihel
  • 5,891
  • 3
  • 16
  • 40
  • Interestingly, those backticks worked too. – road_runner Oct 28 '20 at 17:04
  • However, this isn't particularly good practice either. `seq` isn't built into bash, and neither is it POSIX-stardardized; it isn't guaranteed to exist or work at all, much less work in any particular way. – Charles Duffy Oct 28 '20 at 17:04
  • @road_runner, backticks are legacy pre-POSIX syntax -- when you have a 1970s-era shell they're the only way to do command substitution, but `$(...)` is, as of 1992 (and thus today), the standard -- and it has significant advantages (easier to nest, doesn't change how backslashes behave inside it). – Charles Duffy Oct 28 '20 at 17:06
  • @CharlesDuffy OK, gotcha, it's best to go for `$(...)` and leave backticks to history. – road_runner Oct 28 '20 at 17:33
  • Yup. See [Have backticks in sh shells been deprecated?](https://unix.stackexchange.com/questions/126927/have-backticks-i-e-cmd-in-sh-shells-been-deprecated) for a longer discussion, likewise [BashFAQ #82](http://mywiki.wooledge.org/BashFAQ/082). – Charles Duffy Oct 28 '20 at 17:40