ruk·si

Heredoc

Updated at 2021-10-19 10:18

Here document aka. heredoc is a syntax to pass multiple lines of input to a command. The syntax originated in Unix but the behavior is supported by most shells like Bash and even some programming languages like PHP.

[COMMAND] <<[-]'DELIMITER' [COMMAND_CONTINUES]
HERE-DOCUMENT
DELIMITER
  • You can use any string as the DELIMITER; the most common is EOF.
  • If the DELIMITER is quoted, shell will not replace any included ${VARIABLES}.
  • Using minus sign in the operator <<- makes heredoc to strip any leading tabs.
cat <<EOF
You are $(whoami)
Your home is at $HOME
EOF
# You are ruksi
# Your home is at /home/ruksi

cat <<'EOF'
You are $(whoami)
Your home is at $HOME
EOF
# You are $(whoami)
# Your home is at $HOME

You can continue the command on the same line as << to chain/pipe.

cat <<EOF > greeting.txt && cat greeting.txt && rm greeting.txt
Hello
World!
EOF

Heredoc can also be treated as a file instead of a block of strings.

kubectl apply -f - <<EOF
<KUBERNETES_YAML>
EOF

cat <<EOF | helm install redis -f -
<CHART_CONFIGURATION>
EOF

Sources