【问题标题】:How to prompt user for input in shell script? [duplicate]如何提示用户在 shell 脚本中输入? [复制]
【发布时间】:2017-02-25 07:29:07
【问题描述】:

我有一个 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 脚本中执行此操作?

【问题讨论】:

标签: bash shell scripting


【解决方案1】:

您需要使用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]}" 等方式访问各个元素。

【讨论】:

    猜你喜欢
    • 2010-10-01
    • 2021-02-02
    • 2013-03-23
    • 1970-01-01
    • 2015-10-10
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多