How to use bash Heredoc?


In bash and other shells such as zsh, ksh, etc a Here document (Heredoc) is a type of redirection that allows you to pass multiple lines of input to a command or script. If a programmer needs less amount of text data then using code and data in the same file is a better option it can be done easily using heredoc. These are also used in high-level programming such as PHP, Perl, etc.

In this article, we will discuss how to use heredoc in bash.

The syntax of bash heredoc

The syntax of using heredoc in bash is:

[COMMAND] <<[-] DELIMITER
        HERE-DOCUMENT
DELIMITER

To use heredoc in any bash script you need to use << symbol followed by any delimiting identifier after any bash command and close the heredoc by using the same delimiting identifier at the end of the text.

You can use any string as a delimiting identifier, the most commonly used are EOF or END.

Using heredoc examples

Heredoc is most often used with cat command the basic usage of heredoc is given in the example below.

cat << EOF
You are logged in as $(whoami)
Your home directory is $HOME
EOF

The output will look like this:

You are logged in as lalit
Your home directory is /home/lalit

Using <<- will allow you to indent your code, use it if you are using heredoc inside a statement or loop.

#!/bin/bash

if true; then
  cat <<- END
  Line 1 with a leading tab.
  Line 2 with a leading tab.
  END
fi

You can see the output which is given below.

Line 1 with a leading tab.
Line 2 with a leading tab.

Instead of redirecting the output, you can save it in a file.

cat << EOF > filename.txt
You are logged in as $(whoami)
Your home directory is $HOME
EOF

Using heredoc with SSH

Using Heredoc is one of the most convenient and easiest ways to execute multiple commands on a remote system over SSH. The usage of heredoc with ssh is given in the example below.

ssh -T lalit@192.168.122.175 <<'EOSSH'
VAR1=`pwd`
echo $VAR1

VAR2=$(uname -a)
echo $VAR2

EOSSH

Conclusion

Ok, I hope you understand how to use heredoc in bash. Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.