用脚本参数填充 bash 数组

Fill in bash array with script arguments

我收到一个请求,要在 bash 脚本中将 ip 列表作为数组传递。例如:

./myscript.sh 192.168.0.1,192.168.0.10,192.168.0.15......

上述参数中的 ip 应正确填充 bash 脚本中存在的数组。如果有人可以将它与 getopts utlity 结合使用,我会很高兴。

仅供参考 - 我是 bash 的新手,所以请谅解……

首先您需要从输入中删除逗号,sed 会处理这个问题。 然后,您可以仅使用 var=() 语法创建一个数组。

#! /bin/bash

no_commas=`echo  | sed -e 's/,/ /g'`
ip_array=($no_commas)

for addr in ${ip_array[@]}; do
    echo "Address: $addr"
done

这给了我:

$./bash_array.sh 192.168.1.33,192.168.2.3
Address: 192.168.1.33
Address: 192.168.2.3