bash script use cut command at variable and store result at another variable

帅比萌擦擦* 提交于 2019-12-20 09:39:17

问题


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

I want to ping every ip address in that file

#!/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.


回答1:


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}

You could write your top line as

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

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.




回答2:


You can avoid the loop and cut etc by using:

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

However it would be better if you post a snippet of your config.txt



来源:https://stackoverflow.com/questions/9725897/bash-script-use-cut-command-at-variable-and-store-result-at-another-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!