DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

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!

Top comments (1)

Collapse
 
andywu1998 profile image
andywu1998

so nice, thanks for sharing. expect to update~