读入数组中的大量参数
read in a lot of argument in array
我有一个数组 hnr3[],有 66 个“数据”。
开头都是0
我需要通过参数,例如 (batch.sh arg1 arg2 arg3
) batch.sh /tmp/ 19 33 55
指示脚本 hnr3[19]、hnr3[33] 和 hnr3[55] 应设置为 1。
我的问题是我不知道 hnr3 参数是从 $2、$3 还是 $4 开始,也不知道会有多少。
有没有办法让这个工作,如何? (我是数组部分的新手)
添加:
在参数中添加一个“关键字”怎么样,比如 batch.sh /tmp/ -data 19,33,55
我们将 $* 作为字符串读取,并以某种方式读取 -data[=13= 后面的数据]
如果数字前的参数是可选的,您可以使用 getopts 来处理它们:
#!/bin/bash
manual=0
reset=0
tmpdir=""
while getopts mrt: c; do
case $c in
m) manual=1;;
r) reset=1;;
t) tmpdir="$OPTARG";;
# You can add others optional arguments here
esac
done
shift $((OPTIND - 1))
for arg; do
hnr3[arg]=1
done
declare -p manual
declare -p reset
declare -p tmpdir
declare -p hnr3
调用方式:
./test.sh -m -t /tmp 19 33 55
# results:
declare -- manual="1"
declare -- reset="0"
declare -- tmpdir="/tmp"
declare -a hnr3=([19]="1" [33]="1" [55]="1")
我有一个数组 hnr3[],有 66 个“数据”。
开头都是0
我需要通过参数,例如 (batch.sh arg1 arg2 arg3
) batch.sh /tmp/ 19 33 55
指示脚本 hnr3[19]、hnr3[33] 和 hnr3[55] 应设置为 1。
我的问题是我不知道 hnr3 参数是从 $2、$3 还是 $4 开始,也不知道会有多少。
有没有办法让这个工作,如何? (我是数组部分的新手)
添加:
在参数中添加一个“关键字”怎么样,比如 batch.sh /tmp/ -data 19,33,55
我们将 $* 作为字符串读取,并以某种方式读取 -data[=13= 后面的数据]
如果数字前的参数是可选的,您可以使用 getopts 来处理它们:
#!/bin/bash
manual=0
reset=0
tmpdir=""
while getopts mrt: c; do
case $c in
m) manual=1;;
r) reset=1;;
t) tmpdir="$OPTARG";;
# You can add others optional arguments here
esac
done
shift $((OPTIND - 1))
for arg; do
hnr3[arg]=1
done
declare -p manual
declare -p reset
declare -p tmpdir
declare -p hnr3
调用方式:
./test.sh -m -t /tmp 19 33 55
# results:
declare -- manual="1"
declare -- reset="0"
declare -- tmpdir="/tmp"
declare -a hnr3=([19]="1" [33]="1" [55]="1")