I'm working on a Linux course and during a scripting lesson, the instructor uses a ping-sweeping function as an example. It is meant to iterate through potential IPs on a network from 1 through 255 and return the ones that reply. The code is as follows
#!/bin/bash
for ip in 'seq 1 254'; do
ping -c 1 $1.$ip | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" &
done
This is within a file called ipsweep.sh, which we then call with
./ipsweep.sh [first three tuples of IP]
When I run the script, I get the result
ping: [myIP].seq: Name or service not known
So what I assume is it's not reading seq as a function and simply hitting it and trying to throw it into my script as is. Obviously an IP like 192.168.1.seq doesn't exist so we run into this.
I don't fully understand the syntax of the sequence function because I'm new to Linux and scripting in general, but I've tried using
for ip in (seq 1 254); do
instead but the script won't recognize the parenthesis. Essentially I just need to know how to get the 'seq 1 254' function to work. Any help is greatly appreciated!!
CodePudding user response:
To run a command and return its output, use $()
:
for ip in $(seq 1 254); do
# Note ASCII double quotes
ping -c 1 "$1.$ip" | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" &
done
wait # Wait for all the background processes started in the loop to exit.
Or given you're using bash,
use brace expansion instead of running an external program:
for ip in {1..254}; do
# ...
done
CodePudding user response:
As Shawn mentioned, $() is usually the preferred way to expand commands. But grave accents (or "backticks" as they're sometimes called) can also be used. The issue your code ran into is that it uses the wrong type of accent - acutes (´) instead of graves (`)