Cod*_*ife 21 variables bash loops cut ping
我有一个config.txt文件,IP地址就像这样的内容
10.10.10.1:80
10.10.10.13:8080
10.10.10.11:443
10.10.10.12:80
Run Code Online (Sandbox Code Playgroud)
我想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
Run Code Online (Sandbox Code Playgroud)
我是初学者,抱歉这个问题,但我自己也找不到.
she*_*ter 40
我会使用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}
Run Code Online (Sandbox Code Playgroud)
你可以写上你的顶线
for line in $(cat $file) ; do ...
Run Code Online (Sandbox Code Playgroud)
您需要命令替换$( ... )才能获得分配给$ ip的值
通常认为通过while read line ... done < ${file}模式读取文件中的行更有效.
我希望这有帮助.
您可以使用以下命令来避免循环和剪切等:
awk -F ':' '{system("ping " $1);}' config.txt
Run Code Online (Sandbox Code Playgroud)
但是,如果您发布config.txt的片段会更好