Shell script to read number of inputs and then store it as key value pair

Viewed 27

I am trying to write a shell script where the i have to first read the number of inputs that i am going to pass to the script and then read as many inputs.

Example:

Enter the number of input arguments: 2

If i pass 2, then i have to get 2 pairs of inputs from user and store it as key value pair.

Enter Name: ABC
Enter Subject: Physics

Enter Name: BCD
Enter Subject: Chemistry

If i pass 3, then i have to get 3 pairs of input from user.

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

Output should be like a key value pair.

Is there a way to achieve this shell script ?

What I tried so far: I read the number of input pairs using read -r and using loop try to read as many name and subject. But not sure how to store each name and subject as key value pair.

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

Thank you

1 Answers

I solved this using below. Please suggest if any better approach is there.

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]}"
Related