Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何在shell脚本中提示用户输入?_Bash_Shell_Scripting - Fatal编程技术网

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

Bash 如何在shell脚本中提示用户输入?,bash,shell,scripting,Bash,Shell,Scripting,我有一个shell脚本,在脚本执行时,我想用一个对话框提示用户输入 示例(脚本启动后): “输入要安装的文件:” 用户输入:电子表格工具 其中$1=电子表格,$2=json,$3=diffTool 然后遍历每个用户输入并执行以下操作 for var in "$@" do echo "input is : $var" done 如何在shell脚本中执行此操作?您需要使用bash中提供的read内置命令,并将多个用户输入存储到变量中 read -

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

示例(脚本启动后):

“输入要安装的文件:”
用户输入:电子表格工具
其中$1=电子表格,$2=json,$3=diffTool
然后遍历每个用户输入并执行以下操作

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

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

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


上面的部分以一种方式回答了您的问题,您可以在一个单独的go空格中输入用户输入,但是如果您有兴趣在一个循环中读取多个,并且有多个提示,下面介绍如何在
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]}”
等方式访问各个元素。

我会将文件名作为命令行参数传递。这就是UNIX工具的工作原理。请在提问之前考虑一下。这个确切的问题,以及其他类似的问题,已经被问了很多次了。可能是重复的。这回答了你的问题吗?