bash – 如何在shell脚本中提示用户输入?
发布时间:2020-12-15 17:02:57 所属栏目:安全 来源:网络整理
导读:我有一个 shell脚本,我想在脚本执行时提示用户输入一个对话框. 示例(脚本启动后): "Enter the files you would like to install : "user input : spreadsheet json diffToolwhere $1 = spreadsheet,$2 = json,$3 = diffTool 然后遍历每个用户输入并执行类似
我有一个
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中提供的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中可用 上面的部分回答了你的问题,你可以在一个空格分隔中输入用户输入,但如果你有兴趣在一个循环中读取多个,有多个提示,这里是你在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 "%sn" "${inputArray[@]}" 或者更合适的循环 for arg in "${inputArray[@]}"; do [ ! -z "$arg" ] && printf "%sn" "$arg" done 并将单个元素作为“${inputArray [0]}”,“${inputArray [1]}”等访问. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |