【问题标题】:bash script use cut command at variable and store result at another variablebash 脚本在变量中使用剪切命令并将结果存储在另一个变量中
【发布时间】:2012-04-01 07:48:03
【问题描述】:

我有一个 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

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

【问题讨论】:

  • for line in cat file 将运行两次...一次使用line=cat,一次使用line=file。我不认为那是你想要的。

标签: bash variables loops ping cut


【解决方案1】:

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

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

但是,如果您发布 config.txt 的 sn-p 会更好

【讨论】:

    【解决方案2】:

    我会使用 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 &lt; ${file} 模式通常认为从文件中读取行更有效。

    我希望这会有所帮助。

    【讨论】:

    • +1 不是更高效,而是更安全:for line in $(&lt; file) 将遍历文件中的每个 word,而不是每个 line
    • @yourmother,请注意此处在变量周围使用引号:对于保护值中的空格至关重要。
    • 注意ip可以用ip=${line%%:*}提取,无需调用echo|cut。
    • @glennjackman while IFS=: read -r ip _; do 也可以使用。
    • 这就是我想要的。谢谢!抱歉,我的回答花了这么长时间,但我一直在琢磨如何制作一个好的 USB Linux 版本。顺便说一句,使用 Universal-USB-Installer ^^
    猜你喜欢
    • 2011-02-13
    • 2022-10-19
    • 1970-01-01
    • 2017-06-16
    • 2012-04-03
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多