代码之家  ›  专栏  ›  技术社区  ›  user1156544

在Bash数组中添加元素以稍后打印它们

  •  0
  • user1156544  · 技术社区  · 7 年前

    我正在数组中添加元素( Add a new element to an array without specifying the index in Bash )但我得到了一个意想不到的结果。我想在数组中添加元素和/或迭代数组以打印其值时,我做错了什么。

    代码:

    for name in $(cat list.txt); do
        host $name.$DOMAIN | grep "has address" | cut -d" " -f4
    done
    
    for name in $(cat list.txt); do
        echo "."
        IPS+=(`host $name.$DOMAIN | grep "has address" | cut -d" " -f4`)
        echo ${#IPS[@]}
    done
    
    for ip in $IPS; do
        echo "IP: $ip"
    done
    

    输出:

    12.210.145.45
    67.20.71.219
    75.58.197.10
    31.70.88.22
    .
    1
    .
    3
    .
    4
    .
    4
    .
    4
    IP: 12.210.145.45
    

    预期产量:

    输出:

    12.210.145.45
    67.20.71.219
    75.58.197.10
    31.70.88.22
    .
    1
    .
    2
    .
    3
    .
    4
    IP: 12.210.145.45
    IP: 67.20.71.219
    IP: 75.58.197.10
    IP: 31.70.88.22
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   choroba    7 年前

    要在数组上迭代,请使用

    for ip in "${IPS[@]}" ; do
    

    参见参数 man bash .

    推荐文章