NezzyGuda
NezzyGuda

Reputation: 1

How Do I Separate a Line of Bash Script Over Multiple Lines?

So I've created this ping sweep in a bash terminal, but I want to make a neat looking script file for this:

for IPs in 192.168.0.{1..254}; do ping -c1 -W1 $IPs; done | grep -B1 "1 received" | grep "192.168.0" | cut -d " " -f2 > BashPingSweep.txt

I think I have the for loop correct, but I cant pipe the for loop into the other greps and cut then output. This is what I have now:

#!/bin/bash
for IPs in 192.168.0.{1..254}
do
    ping -c1 -W1 $IPs
done

grep -B1 "1 received"
grep "192.168.0"
cut -d " " -f2
> BashPingSweep.txt

Upvotes: 0

Views: 805

Answers (2)

yacc
yacc

Reputation: 3361

You could try this:

#!/bin/bash

for IP in 192.168.0.{1..254}
do
    ping -c1 -W1 $IP
done |
grep -B1 "1 received" |
grep "192.168.0" |
cut -d " " -f2 \
> BashPingSweep.txt

It looks a bit awkward but it's a common way to format a lengthy pipe over multiple lines. You could also put it like this:

for IP in 192.168.0.{1..254}
do
    ping -c1 -W1 $IP
done \
| grep -B1 "1 received" \
| grep "192.168.0" \
| cut -d " " -f2 \
> BashPingSweep.txt

which is what I prefer because it's easier to see where the pipe goes.

Upvotes: 4

rajeshnair
rajeshnair

Reputation: 1673

You need to pipe it inside the for loop

for IPs in 192.168.0.{1..254};
do
   ping -c1 -W1 $IPs | grep -B1 "1 .* received" | grep "192.168.0" | cut -d " " -f2 > BashPingSweep.txt
done

Upvotes: -2

Related Questions