0

today I started learning bash and I have an issue. I made a script which prompts the user to enter how many elements the want in an array and using a for loop it allows the user enter the elements till the capacity is met. How can I store the data in an array?.

my code:

#!/bin/bash

##Declaring an array to store no.Processes

declare -A execution
    
##Enter number of process
echo "Enter number of Processes: ";
read number_of_process

for ((index=0;index<$number_of_process;index++))
do
i=$(($index+1)) 
    echo "Enter burst time of P$i:";
    read execution
done
echo "Number of Processes = $i";
4
  • 1
    read stores into a variable (or array) a single input line. If you want to append to an array from a read variable, you would do: execution+=("$value") Commented Dec 4, 2021 at 18:49
  • Please can you elaborate more. I am just starting out. Commented Dec 4, 2021 at 18:58
  • BTW, arrays don't exist in sh (they're an extension added by ksh, bash, zsh, etc), so why you have the sh tag on this question is unclear. In general, you should tag for only one shell at a time; and even when the sh executable is provided by bash (which is not the case everywhere: many common operating systems like Ubuntu have sh provided by other implementations such as dash), it turns off several features for better compatibility with the POSIX sh specification when called under that name. Commented Dec 5, 2021 at 16:21
  • @CharlesDuffy thanks for the information. I did not really know about this. Thanks. Commented Dec 10, 2021 at 20:22

1 Answer 1

1

The argument to read can itself be an indexed name.

for ((index=0; index < $number_of_processes; index++)); do
    i=$((index+1)) 
    read -p "Enter burst time of P$i:" 'execution[index]'
done
Sign up to request clarification or add additional context in comments.

1 Comment

@CharlesDuffy Yes, I suppose so. The existence of i confused me, but I guess that's just to present a 1-indexed facade to the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.