Chapter 4: Heredoc
—
When writing shell scripts you may be in a situation where you need to pass a multiline block of text or code to an interactive command. A Here document (Heredoc) is a type of re-direction that allows you to pass multiple lines of input to a command. It uses a token word or delimiter to specify where a document for a command’s standard input should finish. Below is the syntax:
1 [command] <<[delimiter]
2 Here Document
3 delimiter
Below is an example of a heredoc:
1 cat <<EOF
2 Current working directory: $PWD
3 You are logged in as $(whoami)
4 EOF
- Any string can be used as a delimiter, EOF and END are most common.
- If delimiter is unquoted, shell will substitute variables, commands and special characters before passing the here-document lines to the command.If you want to expand variables or do command substitution inside a here-document, you can leave out the single quotes around the delimiter.
- If you really want to indent your here-documents, you can include a hyphen between
<<and the delimiter, i.e.<<-[delimiter]the tabs (but not spaces) at the front of your input lines will be ignored. Use this when your heredoc is inside an if statement for example.
Since bash does not support multiline comments, we can use heredoc to overcome this. If you are not redirecting heredoc to any command, the interpreter will simply read the block of code and will not execute anything:
1 <<- COMMENT
2 This is a comment line 1
3 This is a comment line 2
4 This is a comment line 3
5 COMMENT
Heredoc output can be sent to a file or be piped to another command.