Search code examples
bashshellline

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


I want store in a file and in a variable multiples lines from a "paste" via shell script. A simple read terminates after the first line.

How can I accomplish 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


Solution

  • 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:

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