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

时间:2014-01-03 22:12:08

标签: bash shell lines

我希望将文件存储在一个文件中,并在一个变量中通过shellscript从“粘贴”中获取多行。

我怎样才能完成这个?

示例:

echo "Paste the  certificate key:" 

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

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

1 个答案:

答案 0 :(得分:29)

你只需要决定阅读多少。

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

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

如果您希望稍后在脚本中继续阅读,您可以阅读,直至看到空行:

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

如果你想让它感觉更像魔术,你可以阅读,直到脚本没有输入两秒钟:

#!/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!"