您需要使用bash
中提供的内置read
函数,并将多个用户输入存储到变量中。
read -p "Enter the files you would like to install: " arg1 arg2 arg3
请以空格分隔您的输入。例如,当运行以上代码时:
Enter the files you would like to install: spreadsheet json diffTool
现在,上述每个输入都可以在变量arg1
、arg2
和arg3
中使用。
上面的部分以一种方式回答了你的问题,你可以一次性用空格分隔符输入用户输入,但是,如果你有兴趣循环读取多个带有多个提示符的用户输入,在 bash
shell 中可以这样做。下面的逻辑会获取用户的输入,直到按下 Enter 键。
#!/bin/bash
input="junk"
inputArray=()
while [ "$input" != "" ]
do
read -p "Enter the files you would like to install: " input
inputArray+=("$input")
done
现在您所有的用户输入都存储在数组inputArray
中,您可以循环遍历以读取这些值。若要一次性打印它们,请执行
printf "%s\n" "${inputArray[@]}"
或者更加合适的循环方式是
for arg in "${inputArray[@]}"; do
[ ! -z "$arg" ] && printf "%s\n" "$arg"
done
并且可以像这样访问单个元素"${inputArray[0]}"
,"${inputArray[1]}"
等。