bash Heredocs And Herestrings - ghdrako/doc_snipets GitHub Wiki

Heredocs

echo "Let's test abc:"
if [[ abc = a* ]]; then
    cat <<END
        abc seems to start with an a!
END
fi

Result:
Let's test abc:
        abc seems to start with an a!

If you use <<-END instead of ``<<END` as your Heredoc operator, Bash removes any tab characters in the beginning of each line of your Heredoc content before sending it to the command. That way you can still use tabs (but not spaces) to indent your Heredoc content with the rest of your code. Those tabs will not be sent to the command that receives your Heredoc. You can also use tabs to indent your sentinel string.

Bash substitutions are performed on the contents of the Heredoc by default. However, if you quote the word that you're using to delimit your Heredoc, Bash won't perform any substitutions on the contents. Try this example with and without the quote characters, to see the difference:

$ cat <<'XYZ'
> My home directory is $HOME
> XYZ
My home directory is $HOME

The most common use of Heredocs is dumping documentation to the user:

usage() {
    cat <<EOF
usage: foobar [-x] [-v] [-z] [file ...]
A short explanation of the operation goes here.
It might be a few lines long, but shouldn't be excessive.
EOF
}

Herestring

$ grep proud <<<"I am a proud sentence"
I am a proud sentence.

This time, stdin reads its information straight from the string you put after the <<< operator. This is very convenient to send data that's in variables into processes:

$ grep proud <<<"$USER sits proudly on his throne in $HOSTNAME."
lhunath sits proudly on his throne in Lyndir.

Herestrings are shorter, less intrusive and overall more convenient than their bulky Heredoc counterpart. However, they are not portable to the Bourne shell.

Later on, you will learn about pipes and how they can be used to send the output of a command into another command's stdin. Many people use pipes to send the output of a variable as stdin into a command. However, for this purpose, Herestrings should be preferred. They do not create a subshell and are lighter both to the shell and to the style of your shell script:

$ echo 'Wrap this silly sentence.' | fmt -t -w 20
Wrap this silly
   sentence.
$ fmt -t -w 20 <<< 'Wrap this silly sentence.'
Wrap this silly
   sentence.

Technically, Heredocs and Herestrings are themselves redirects just like any other. As such, additional redirections can occur on the same line, all evaluated in the usual order.

$ cat <<EOF > file
> My home dir is $HOME
> EOF
$ cat file
My home dir is /home/greg
⚠️ **GitHub.com Fallback** ⚠️