问题描述
我有一个 config.txt 文件,其IP地址是这样的内容
I have a config.txt file with IP addresses as content like this
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
我是一个初学者,很抱歉出现这样的问题,但我自己却找不到.
I'm a beginner, sorry for such a question but I couldn't find it out myself.
推荐答案
awk解决方案是我要使用的解决方案,但是如果您想了解bash的问题,请参见脚本的修订版.
The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
#!/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的值
You needed command substitution $( ... )
to get the value assigned to $ip
通常使用while read line ... done < ${file}
模式从文件中读取行更有效.
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
我希望这会有所帮助.
这篇关于bash脚本在变量处使用cut命令,并将结果存储在另一个变量处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!