如何在Shell脚本中提示用户输入?

9

我有一个shell脚本,希望在执行时向用户显示一个对话框以提示用户输入。

示例(脚本启动后):

"Enter the files you would like to install : "

user input : spreadsheet json diffTool

where $1 = spreadsheet, $2 = json, $3 = diffTool

然后循环遍历每个用户输入并执行类似的操作。
for var in "$@"
do
    echo "input is : $var"
done

我该如何在我的shell脚本中实现这个功能?

2
我会将文件名作为命令行参数传递。这就是大多数UNIX工具的工作方式。 - hek2mgl
在提问之前,请先搜索。这个问题以及类似的问题已经被问过很多次了。 - dimo414
可能是Shell脚本用户提示/输入的重复问题。 - jww
2
这个回答解决了你的问题吗? [如何在Bash中将用户输入读入变量?] (https://dev59.com/mmMl5IYBdhLWcg3wRlLo) - Josh Correia
1个回答

21

您需要使用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

现在,上述每个输入都可以在变量arg1arg2arg3中使用。


上面的部分以一种方式回答了你的问题,你可以一次性用空格分隔符输入用户输入,但是,如果你有兴趣循环读取多个带有多个提示符的用户输入,在 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]}"等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接