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.

John Wick
  • 29
  • 1
  • 1
  • 7

2 Answers2

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
UtLox
  • 3,744
  • 2
  • 10
  • 13
  • script.sh: 2: read: Illegal option -a script.sh: 3: script.sh: Bad substitution – John Wick May 15 '19 at 10:18
  • @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?](https://stackoverflow.com/q/14594033/4154375). – pjh May 15 '19 at 18:20
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

PilouPili
  • 2,601
  • 2
  • 17
  • 31