DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

3 2

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
andywu1998 profile image
andywu1998

so nice, thanks for sharing. expect to update~

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs