Unix Heredoc Cheatsheet

clavinjune

Clavin June

Posted on January 13, 2022

Unix Heredoc Cheatsheet

Photo by @kellysikkema on Unsplash

Syntax

[cmd] <<[-] delimeter [cmd]
    contents
delimeter
Enter fullscreen mode Exit fullscreen mode

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

cat <<EOF
    echo "$HOME"
EOF
Enter fullscreen mode Exit fullscreen mode

result:

    echo "/home/clavinjune"
Enter fullscreen mode Exit fullscreen mode

Escape Variable

Use \$ instead of $ to escape specific variable

cat <<EOF
    echo "$HOME"
    echo "\$HOME"
EOF
Enter fullscreen mode Exit fullscreen mode

result:

    echo "/home/clavinjune"
    echo "$HOME"
Enter fullscreen mode Exit fullscreen mode

Escape All Variables

Use 'EOF' instead of EOF to escape all variables

cat <<'EOF'
    echo "$HOME"
    echo "\$HOME"
EOF
Enter fullscreen mode Exit fullscreen mode

result:

    echo "$HOME"
    echo "\$HOME"
Enter fullscreen mode Exit fullscreen mode

Remove Leading Tab

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

cat <<-EOF
    echo "$HOME"
    echo "\$HOME"
EOF
Enter fullscreen mode Exit fullscreen mode

result:

echo "/home/clavinjune"
echo "$HOME"
Enter fullscreen mode Exit fullscreen mode

Add More Pipeline

cat <<EOF | grep june
    echo "$HOME"
    echo "\$HOME"
EOF
Enter fullscreen mode Exit fullscreen mode

result:

    echo "/home/clavinjune"
Enter fullscreen mode Exit fullscreen mode

Write To a File

cat <<-'EOF' > /tmp/foo
    echo "$HOME"
    echo "\$HOME"
EOF
Enter fullscreen mode Exit fullscreen mode

result:

$ cat /tmp/foo 
echo "$HOME"
echo "\$HOME"
Enter fullscreen mode Exit fullscreen mode

Thank you for reading!

💖 💪 🙅 🚩
clavinjune
Clavin June

Posted on January 13, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Unix Heredoc Cheatsheet
unix Unix Heredoc Cheatsheet

January 13, 2022