如何在 Bash 脚本中读取多行输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20913635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:09:18  来源:igfitidea点击:

How to read multi-line input in a Bash script?

bashshelllines

提问by Alan

I want store in a file and in a variable multiples lines from a "paste" via shellscript.

我想通过shellscript存储在一个文件和一个来自“粘贴”的可变倍数行中。

How can I acomplish that?

我怎样才能做到这一点?

Example:

例子:

echo "Paste the  certificate key:" 

1fv765J85HBPbPym059qseLx2n5MH4NPKFhgtuFCeU2ep6B19chh4RY7ZmpXIvXrS7348y0NdwiYT61
1RkW75vBjGiNZH4Y9HxXfQ2VShKS70znTLxlRPfn3I7zvNZW3m3zQ1NzG62Gj1xrdPD7M2rdE2AcOr3
Pud2ij43br4K3729gbG4n19Ygx5NGI0212eHN154RuC4MtS4qmRphb2O9FJgzK8IcFW0sTn71niwLyi
JOqBQmA5KtbjV34vp3lVBKCZp0PVJ4Zcy7fd5R1Fziseux4ncio32loIne1a7MPVqyIuJ8yv5IJ6s5P
485YQX0ll7hUgqepiz9ejIupjZb1003B7NboGJMga2Rllu19JC0pn4OmrnxfN025RMU6Qkv54v2fqfg
UmtbXV2mb4IuoBo113IgUg0bh8n2bhZ768Iiw2WMaemgGR6XcQWi0T6Fvg0MkiYELW2ia1oCO83sK06
2X05sU4Lv9XeV7BaOtC8Y5W7vgqxu69uwsFALripdZS7C8zX1WF6XvFGn4iFF1e5K560nooInX514jb
0SI6B1m771vqoDA73u1ZjbY7SsnS07eLxp96GrHDD7573lbJXJa4Uz3t0LW2dCWNy6H3YmojVXQVYA1
v3TPxyeJD071S20SBh4xoCCRH4PhqAWBijM9oXyhdZ6MM0t2JWegRo1iNJN5p0IhZDmLttr1SCHBvP1
kM3HbgpOjlQLU8B0JjkY8q1c9NLSbGynKTbf9Meh95QU8rIAB4mDH80zUIEG2qadxQ0191686FHn9Pi

read it and store it file say /tmp/$keyfile read it and store it in a variable $keyvariable

读取它并将其存储文件说 /tmp/$keyfile 读取它并将其存储在变量 $keyvariable 中

回答by that other guy

You just have to decide how much to read.

你只需要决定阅读多少。

If this is the only input, you could read until end of file. This is how most UNIX utilities work:

如果这是唯一的输入,您可以读取到文件末尾。这是大多数 UNIX 实用程序的工作方式:

#!/bin/bash
echo "Pipe in certificate, or paste and it ctrl-d when done"
keyvariable=$(cat)

If you want to continue reading things later in the script, you can read until you see a blank line:

如果您想继续阅读脚本中的内容,可以阅读直到看到一个空行:

#!/bin/bash
echo "Paste certificate and end with a blank line:"
keyvariable=$(sed '/^$/q')

If you want it to feel more like magic interactively, you could read until the script has gone two seconds without input:

如果您希望它以交互方式感觉更像魔术,您可以阅读,直到脚本在没有输入的情况下运行两秒钟:

#!/bin/bash
echo "Paste your certificate:"
IFS= read -d '' -n 1 keyvariable   
while IFS= read -d '' -n 1 -t 2 c
do
    keyvariable+=$c
done
echo "Thanks!"