我的任务是使用数组更新脚本,以便它可以运行多个域。事实是,我不太熟悉循环数组。我已经在网上进行了一些搜索,但是我还没有完全理解如何将数组添加到此处已有的数组中。那对我来说毫无意义。我了解(我认为)数组是如何工作的,但是当我尝试实现数组时,会出现大量错误。任何建议/提示都会有所帮助。
当前,此代码可以完美运行。但一次只能使用一个域。
即使不是数组,也要寻求有关最佳选择的建议。
#distribution.sh
#Gathers info and creates the .json file needed to create distribution information for AWS domain sites
#Gather web-id and assign it to the variable "webid"
echo "Insert the webid for the site you are working with:"
read webid
#Gather sub domain info (www) for the site in question and assign it to the variable "subdomain"
echo "Insert the sub domain name for the site you are working with:"
read subdomain
#Gather domain info (domain.com) for the site in question and assign it to the variable "domain"
echo "Insert the domain name for the site you are working with:"
read domain
#Check spelling with the user
printf "Your WebID is: $webid\nYour sub domain is: $subdomain\nYour domain
is: $domain\n"
read -p "Is this correct? y/n " -n 1 -r
echo #
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
exit 1
else
printf "{\n \"web_ids\": [\n {\n \"web_id\": \"$webid\",\n
\"domains\": {\n \"$domain\": {\n \"vhosts\": [\n
\"$domain\",\n \"$subdomain.$domain\"\n ]\n }\n
}\n }\n ]\n}\n\n" > $domain.json
#Run create-distribution on our newly created .json file
create-distribution $domain.json
#Display the arn line from the .json file after the fact so we can copy it into case notes per process
cat $domain.json | grep dist
fi
答案 0 :(得分:1)
这是一个简短的重构,它避免了使用read
进行讨厌的交互式输入,并删除了一些常见的shell反模式,并修复了缩进的问题。我已经用内联注释替换了您的注释,这些注释更详细地记录了重构。
这只是在here document上循环,所以这里没有数组。
#!/bin/sh
# Read input data from a here document
while read -r webid subdomain domain; do
# use printf the way $dmr intended
# print diagnostics to stderr
printf "%s: Your WebID is: %s\nYour sub domain is: %s\nYour domain is: %s\n" "$0" "$webid" "$subdomain" "$domain" >&2
# use single quotes to reduce backslashitis in format string
printf '{\n "web_ids": [\n {\n "web_id": "%s",\n "domains": {\n "%s": {\n "vhosts": [\n "%s",\n "%s.%s"\n ]\n }\n }\n }\n ]\n}\n\n' "$webid" "$domain" "$domain" "$subdomain" "$domain" > "$domain".json
# maybe this could read stdin to avoid temp file?
create-distribution "$domain".json
# avoid useless use of cat
grep dist "$domain".json
# you should probably use a proper JSON tool like jq though
#jq -c .dist "$domain".json
done <<\____
firstwebid its-subdomain itsdomain
secondwebid subdomain-for-second domainforsecond
____
这是\____
和____
之间的文字;文档中的每一行都提供while ... done
循环的一次迭代的值,以填充read
语句中的三个变量。
数组在这里并不是特别合适,因为您有二维矩阵。您可以遍历同步索引,但是在我看来,这很复杂。
webids=(first second third)
domains=(one two three)
subdomains=(one other different)
for ((i=0; i<${#webids[@]}; ++i)); do
printf '...' "${webids[i]}" "${domains[i]}" "${subdomains[i]}"
done
正如您所看到的,只要您有非常小的数组,这种方法就可以工作,但是一旦您在每个数组中获得了大约六个以上的项目,它就会变得很烦人-使它们保持同步,以便第21个项目第一个数组中的第一个对应于第21个项目,另外两个中的第21个成为其自身的繁琐工作,如果将每个条目都放在一个位置(如here文档中),则很容易避免。