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!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay