bash脚本在变量处使用cut命令并将结果存储在另一个变量中

时间:2012-03-15 18:29:49

标签: bash variables loops ping cut

我有一个 config.txt 文件,其IP地址就像这样的内容

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

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

2 个答案:

答案 0 :(得分:36)

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

##config file with ip addresses like 10.10.10.1:80
#!/bin/bash -vx
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}模式,

通常认为从文件读取行更有效。

我希望这会有所帮助。

答案 1 :(得分:7)

您可以使用:

来避免循环和剪切等
awk -F ':' '{system("ping " $1);}' config.txt

但是,如果你发布config.txt的片段

会更好
相关问题