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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42453262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:49:12  来源:igfitidea点击:

How to prompt user for input in shell script?

bashshellscripting

提问by danynl

I have a shell script in which I would like to prompt the user with a dialog box for inputs when the script is executed.

我有一个 shell 脚本,我想在脚本执行时用一个对话框提示用户输入。

example (after script has started) :

示例(脚本启动后):

"Enter the files you would like to install : "

user input : spreadsheet json diffTool

where  = spreadsheet,  = json,  = diffTool

then loop through each user input and do something like

然后遍历每个用户输入并执行类似的操作

for var in "$@"
do
    echo "input is : $var"
done

How would I go about doing this within my shell script?

我将如何在我的 shell 脚本中执行此操作?

Thank you in advance

先感谢您

回答by Inian

You need to use the readbuilt-in available in bashand store the multiple user inputs into variables,

您需要使用read内置的可用bash并将多个用户输入存储到变量中,

read -p "Enter the files you would like to install: " arg1 arg2 arg3

Give your inputs separated by space. For example, when running the above,

输入以空格分隔的输入。例如,当运行上述时,

Enter the files you would like to install: spreadsheet json diffTool

now each of the above inputs are available in the variables arg1,arg2and arg3

现在上述每个输入都在变量中可用arg1arg2并且arg3



The above part answers your question in way, you can enter the user input in one go space separated, but ifyou are interested in reading multiple in a loop, with multiple prompts, here is how you do it in bashshell. The logic below get user input until the Enterkey is pressed,

以上部分以某种方式回答了您的问题,您可以在一个空格中输入用户输入,但是如果您有兴趣在循环中阅读多个并带有多个提示,那么您可以在bashshell 中执行此操作。下面的逻辑获取用户输入,直到Enter按键被按下,

#!/bin/bash

input="junk"
inputArray=()

while [ "$input" != "" ] 
do 
   read -p "Enter the files you would like to install: " input
   inputArray+=("$input")
done

Now all your user inputs are stored in the array inputArraywhich you can loop over to read the values. To print them all in one shot, do

现在您的所有用户输入都存储在数组中inputArray,您可以循环读取这些值。要将它们全部打印出来,请执行

printf "%s\n" "${inputArray[@]}"

Or a more proper loop would be to

或者更合适的循环是

for arg in "${inputArray[@]}"; do
    [ ! -z "$arg" ] && printf "%s\n" "$arg"
done

and access individual elements as "${inputArray[0]}", "${inputArray[1]}"and so on.

并访问单个元素作为"${inputArray[0]}""${inputArray[1]}"等等。