我正在编写一段bash脚本。我目前遇到的问题是如何同时接受用户的多个输入。
具体来说,当脚本要求输入时,用户必须能够输入多个域名。
例如,脚本运行部分:
Enter the domain names :
用户必须能够逐行输入域名,可以手动输入每个域名或者从其他地方复制域名列表并粘贴到脚本输入框中,如下所示:
domain1.com
domain2.com
domain3.com
domain4.com
这个可能吗?
loop
:#!/bin/bash
arrDomains=()
echo "Enter the domain names :"
while read domain
do
arrDomains+=($domain)
# do processing with each domain
done
echo "Domain List : ${arrDomains[@]}"
当您输入完所有的域名后,按下ctrl + D
来结束输入。
是的,你可以使用readarray
命令:
printf "Enter the domain names: "
readarray -t arr
# Do something...
declare -p arr
上面的最后一行只是记录了bash现在看到的数组。
用户可以输入或复制粘贴数组名称。当用户完成后,他在一行开头键入Ctrl-D。
示例:
$ bash script
Enter the domain names: domain1.com
domain2.com
domain3.com
domain4.com
declare -a arr='([0]="domain1.com" [1]="domain2.com" [2]="domain3.com" [3]="domain4.com")'
declare -p
应该做什么,但它绝对没有将其放入变量中。https://gist.github.com/hopeseekr/460700d166487dcd11d2dbd5f36b8077 - Theodore R. Smithdeclare -p arr
的目的是将变量的内容打印到标准输出。在答案中的示例中,declare -p
行是产生输出 eclare -a arr='([0]="domain1.com" [1]="domain2.com" [2]="domain3.com" [3]="domain4.com")'
的代码行。 - John1024所以@John1024的答案真的为我指明了正确的方向,但对于如何将这些数据不仅分配给变量,而且重要的是保留空格和换行符,我仍然感到非常困惑。
经过许多StackOverflow和StackExchange的答案后,我创建了以下代码片段,展示了如何实现。它来自我的Uber BashScripts项目 @ wifi-autorun-on-connect.installer:
#############################################################
# Grab the script from an existing file -or- user input... #
# #
# Copyright © 2020 Theodore R. Smith #
# License: Creative Commons Attribution v4.0 International #
# From: https://github.com/hopeseekr/BashScripts/ #
# @see https://dev59.com/K5nga4cB1Zd3GeqPbJ_l#64486155 #
#############################################################
function grabScript()
{
if [ ! -z "$1" ] && [ -f "$1" ]; then
echo $(<"$1")
else
echo "" >&2
echo "Please type/paste in bash script you wish to be run when NetworkManager connects to '${HOTSPOT}'." >&2
echo "Press CTRL+D when finished." >&2
echo "You should start with '#!/bin/bash'..." >&2
echo "" >&2
# Read user input until CTRL+D.
# @see https://dev59.com/K5nga4cB1Zd3GeqPbJ_l#38811806
readarray -t user_input
# Output as a newline-dilemeted string.
# @see https://dev59.com/U2Uo5IYBdhLWcg3w5Sul#15692004
printf '%s\n' "${user_input[@]}"
fi
}
SCRIPT=$(grabScript "$2")
# Preserve white spaces and newlines.
# @see https://dev59.com/7mMl5IYBdhLWcg3w7qhq#18018422
echo "$SCRIPT"
以下是我在需要让BASH脚本要求pem格式证书的情况下所做的事情:
echo "Paste your multi-line text into the terminal, ending with two blank lines"
while [ 1 ]; do
read line
echo $line >> file.txt
lastline=$line
if [ "${lastline}${line}" == "" ]; then break; fi
done