Here Doc, Here Strings

1. Here Doc

1.1 Basic syntax

The here document (<<) can be used to pass a multi-line block of text or code to an interactive command

1.11 Example with cat

1.12 Example with python3

Explanation of Python3 features and functions used

a. python3 -

When the script name is given as '-', it refers to the standard input

b. sys.stdout.write

  • Writes data to standard output (stdout)

  • Prints Hello here doc!

  • The here-document will feed text into stdin of python3

  • The pipe (|) performs the following: stdout of python3 -> stdin of cat

    • Prints 12345678

  • The here-document will feed text into stdin of python3

  • The redirection (>>) will append the stdout of python3 to the file outfile

    • Appends 12345678 to the file

1.13 Example with while loop + read

  • Print each value in the array from stdout

    • echo prints to the stdout (fd 1)

  • Print each value in the array from stderr

    • 1>&2 redirects stdout to stderr

  • >> outfile append stdout to the outfile file

    • The file outfile will contain the value: 0 1 2 A B C D

  • Notice that even with the >> outfile command the data is not actually written to the file, but instead printed on the terminal

    • This is due to the 1>&2 command redirecting stdout to stderr

    • The value in stderr will be printed on the terminal

  • The file outfile will be empty

  • Notice that the output is empty

    • This is due to the &>/dev/null command at the end which redirect all the stout and stderr to the /dev/null file

2. Here Strings

2.1 Basic syntax

The here string (<<<) command is used for input redirection from a text or variable

2.12 Input redirection from a text

  • Both commands shown below are equivalent

    • outputs hr

2.13 Input redirecton from a variable

Last updated