Bash Heredoc and Using Heredoc with SSH

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, such as [tee](https://linuxize.com/post/linux-tee-command/)cat, or [sftp](https://linuxize.com/post/how-to-use-linux-sftp-command-to-transfer-files/).

In Bash and other shells like Zsh, a Here document (Heredoc) is a type of redirection that allows you to pass multiple lines of input to a command.

The syntax of writing HereDoc takes the following form:

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

Copy

  • The first line starts with an optional command followed by the special redirection operator << and the delimiting identifier.
  • You can use any string as a delimiting identifier, the most commonly used are EOF or END.
  • If the delimiting identifier is unquoted, the shell will substitute all variables, commands and special characters before passing the here-document lines to the command.
  • Appending a minus sign to the redirection operator <<-, will cause all leading tab characters to be ignored. This allows you to use indentation when writing here-documents in shell scripts. Leading whitespace characters are not allowed, only tab.
  • The here-document block can contain strings, variables, commands and any other type of input.
  • The last line ends with the delimiting identifier. White space in front of the delimiter is not allowed.

Basic Heredoc Examples

In this section, we will look at some basic examples of how to use heredoc.

Heredoc is most often used in combination with the cat command.

#bash #bash heredoc #ssh

Bash Heredoc and Using Heredoc with SSH
17.80 GEEK