简体   繁体   English

如何在多行中分隔一行Bash脚本?

[英]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: 因此,我在bash终端中创建了此ping扫描,但是我想为此编写一个简洁的脚本文件:

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. 我认为我的for循环是正确的,但是我无法将for循环传送到其他收集器中,然后剪切然后输出。 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循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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