Shell脚本读取输入的数量,然后将其存储为键值对



我正在尝试编写一个shell脚本,其中我必须首先读取要传递给脚本的输入数,然后读取尽可能多的输入。

示例:

Enter the number of input arguments: 2

如果我通过2,那么我必须从用户那里获得2对输入,并将其存储为键值对。

Enter Name: ABC
Enter Subject: Physics
Enter Name: BCD
Enter Subject: Chemistry

如果我通过3,那么我必须从用户那里获得3对输入。

Enter the number of input arguments: 3
Enter Name: ABC
Enter Subject: Physics
Enter Name: ABC
Enter Subject: Chemistry
Enter Name: ABC
Enter Subject: Maths

输出应该像键值对一样。

有没有办法实现这个shell脚本?

到目前为止我尝试过的:我使用read-r读取输入对的数量,并使用循环尝试读取尽可能多的名称和主题。但不确定如何将每个名称和主题存储为键值对。

printf "Enter number of input pairs:" 
read -r count
current_iter=0
until [ "current_iter" -ge ${count} ]
do
printf "Enter Name:"
read -r name
printf "Enter Subject:"
read -r subject
current_iter=$((current_iter+1))
done

谢谢

我用下面的方法解决了这个问题。请建议是否有更好的方法。

printf "Enter number of input pairs:" 
read -r count
current_iter=0 #counter for loop
delicate -A name_sub #array for key value pair
until [ "current_iter" -ge ${count} ]
do
printf "Enter Name:"
read -r name
printf "Enter Subject:"
read -r subject
name_sub[${name}]=${subject}
current_iter=$((current_iter+1))
done
for key in "${!name_sub[@]}"; do
echo "Name is: $key and Subject is: ${name_sub[$key]}"

最新更新