简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM