How-to: Use a 'Here Document'

A here document is a block of text or code which is redirected to an interactive program or a command.

#!/bin/bash
Command <<MyUniqueLimitString
some text
some more text
MyUniqueLimitString

The above is equivalent to Command < tempfile.txt where the tempfile contains the text required.

EOF and END are often chosen as the MyUniqueLimitString but any string can be used as long as it does not appear within the here document text.

The - option to mark a here document limit string (<<-LimitString) will suppress leading tabs (but not spaces) in the output. This allows the use of indentation (with tabs) when writing here-documents in shell scripts making them more readable.

Here documents can also be used to supply values to variables or functions.

Examples

Pass multiple lines of text to cat

#!/bin/bash
cat <<End-of-text
--------------------------
The quick brown fox
jumped over the lazy dog
--------------------------
End-of-text

To also write the text to a file, change cat to cat > $filename

Substituting values from a variable (or more likely a parameter to the script) makes it possible to alter the body of the here document:

#!/bin/bash
ACTION="Quickly"

cat <<End-of-txt
The quick brown fox $ACTION
jumped over the lazy dog
End-of-txt

To disable parameter substitution put quotes around the limit string: <<"End-of-message"

Start mysql passing multiple variables for username/password:

#!/bin/bash
DB_NAME="db064"
PASSWORD="Pa$$w0rd"
APP_USER="user64"
APP_PASSWORD="cfE7JcEbgzW1XUUaEQ"

mysql -u root --password="${PASSWORD}" <<EOF
CREATE DATABASE ${DB_NAME};
CREATE USER '${APP_USER}'@'localhost' IDENTIFIED BY '${APP_PASSWORD}';
GRANT ALL ON ${DB_NAME}.* TO '${APP_USER}'@'localhost'
EOF

Related linux commands:

Here Strings
BASH Syntax
Windows PowerShell equivalent: Here strings


 
Copyright © 1999-2022 SS64.com
Some rights reserved