Shell脚本从用户读取多个输入

时间:2019-05-15 09:31:36

标签: bash shell

如何一次从用户读取任意数量的输入并将其存储到数组中。 例如,这一次只能读取一个输入

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

我想要类似的东西

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

我如何将位置名称存储到数组中,然后遍历它。

2 个答案:

答案 0 :(得分:2)

尝试一下:

#!/bin/bash
read -r -p "Please enter location names separated by space: " -a arr
for location in "${arr[@]}"; do 
   echo "$location"
done

答案 1 :(得分:1)

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

for location in $location_names
do
echo $location
done

测试。

  

请输入用空格分隔的位置名称:巴黎伦敦纽约
  巴黎
  伦敦
  纽约