Unix Heredoc Cheatsheet

tech · Jan 13, 2022 · ~1 min
Photo by @kellysikkema on Unsplash
Photo by @kellysikkema on Unsplash

Syntax

1
2
3
[cmd] <<[-] delimeter [cmd]
    contents
delimeter

All contents will be passed to the cmd as an input, examples below will use EOF as a delimeter and cat as a command, you can change to whatever you want.

With Variable

1
2
3
cat <<EOF
    echo "$HOME"
EOF

result:

1
    echo "/home/clavinjune"

Escape Variable

Use \$ instead of $ to escape specific variable

1
2
3
4
cat <<EOF
    echo "$HOME"
    echo "\$HOME"
EOF

result:

1
2
    echo "/home/clavinjune"
    echo "$HOME"

Escape All Variables

Use 'EOF' instead of EOF to escape all variables

1
2
3
4
cat <<'EOF'
    echo "$HOME"
    echo "\$HOME"
EOF

result:

1
2
    echo "$HOME"
    echo "\$HOME"

Remove Leading Tab

Use <<- instead of << to remove leading tabs

1
2
3
4
cat <<-EOF
    echo "$HOME"
    echo "\$HOME"
EOF

result:

1
2
echo "/home/clavinjune"
echo "$HOME"

Add More Pipeline

1
2
3
4
cat <<EOF | grep june
    echo "$HOME"
    echo "\$HOME"
EOF

result:

1
    echo "/home/clavinjune"

Write To a File

1
2
3
4
cat <<-'EOF' > /tmp/foo
    echo "$HOME"
    echo "\$HOME"
EOF

result:

1
2
3
$ cat /tmp/foo 
echo "$HOME"
echo "\$HOME"

Thank you for reading!

· · ·

Love This Content?

Any kind of supports is greatly appreciated! Kindly support me via Bitcoin, Ko-fi, Trakteer, or just continue to read another content. You can write a response via Webmention and let me know the URL via Telegraph.

Drop Your Comment Below