1

How to read any number of inputs from user at once and store it into an array. For example this will read only a single input at a time

  read -p "Please enter username: " username
  echo "Dear $username,"

I want something like:

read -p "Please enter location names separated by space: "

How would i store location names into an array and then loop through it.

2 Answers 2

3

try this:

#!/bin/bash
read -r -p "Please enter location names separated by space: " -a arr
for location in "${arr[@]}"; do 
   echo "$location"
done
Sign up to request clarification or add additional context in comments.

2 Comments

script.sh: 2: read: Illegal option -a script.sh: 3: script.sh: Bad substitution
@JohnWick, the code is good(ish) Bash code. read in Bash has had the -a option for a very long time, so I suspect that you are running the code with another shell, possibly Dash. If you run the code with bash script.sh, or make the program executable and run it with ./script.sh, it should work unless you are using a decades-old version of Bash. You can't do what you want with Dash because it doesn't support arrays. See Does dash support bash style arrays?.
1
read -p "Please enter location names separated by space: " location_names

for location in $location_names
do
echo $location
done

Testing.

Please enter location names separated by space: paris london new-york
paris
london
new-york

2 Comments

Thanks, it worked. But how location_names becomed an array ?
for parses location_names with the space separator, technically location_names did not become an array

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.