如何在shell脚本中提示用户输入? [英] How to prompt user for input in shell script?

查看:680
本文介绍了如何在shell脚本中提示用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Shell脚本,在该脚本中,执行脚本时,我会在对话框中提示用户输入内容.

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.

示例(脚本启动后):

"Enter the files you would like to install : "

user input : spreadsheet json diffTool

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

然后遍历每个用户输入并做类似

then loop through each user input and do something like

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

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

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

提前谢谢

推荐答案

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

You need to use the read built-in available in bash and store the multiple user inputs into variables,

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

现在上述每个输入都在变量arg1arg2arg3

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

以上部分以一种方式回答了您的问题,您可以在一个空格内输入用户输入的内容,但是如果您对循环阅读多个内容感兴趣,并带有多个提示,这是在bash shell中执行此操作的方法.按下 Enter 键之前,下面的逻辑将获取用户输入,

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

#!/bin/bash

input="junk"
inputArray=()

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

现在,所有用户输入都存储在数组inputArray中,您可以循环遍历以读取值.要一次打印所有内容,

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

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

或者更合适的循环是

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

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

这篇关于如何在shell脚本中提示用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆