27

我有一个带有 IP 地址的config.txt文件,内容如下

10.10.10.1:80
10.10.10.13:8080
10.10.10.11:443
10.10.10.12:80

我想ping该文件中的每个IP地址

#!/bin/bash
file=config.txt

for line in `cat $file`
do
  ##this line is not correct, should strip :port and store to ip var
  ip=$line|cut -d\: -f1
  ping $ip
done

我是初学者,很抱歉这样的问题,但我自己找不到。

4

2 回答 2

54

我会使用 awk 解决方案,但是如果您想了解 bash 的问题,这里是您的脚本的修订版本。

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

你可以把你的第一行写成

for line in $(cat $file) ; do ...

(但不推荐)。

您需要命令替换$( ... )来获得分配给 $ip 的值

从文件中读取行通常被认为使用该while read line ... done < ${file}模式更有效。

我希望这有帮助。

于 2012-03-15T18:48:25.567 回答
9

您可以使用以下方法避免循环和剪切等:

awk -F ':' '{system("ping " $1);}' config.txt

但是,如果您发布 config.txt 的片段会更好

于 2012-03-15T18:33:56.733 回答