Here string in shell

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the bash category.

Last Updated: 2024-04-25

<<< is known as a here string in shell.

Purpose 1: Pass a string to STDIN

You can use it to pass a string into STDIN instead of a file, as you might do with redirection.

$ wc -c Gemfile
 when Gemfile given as an argument, it is printed in results
# 4280 Gemfile

wc -c <Gemfile
# when given with redirection is does not print filename
# 4280

# with a heredoc, I just give it a string:
wc -c <<< "This is my content"
# 19

Purpose 2: Avoid vanishing sub-shell scope of pipes

Look at the following code. Take it as a given that read will assign the 1st and 2nd words to the variables first and second

Quiz: What gets printed (in bash)?

echo "hello world" | read first second
echo $second $first

Answer: Just an empty space!

(By contrast, FYI, ZSH prints "world hello" as you might expect.

But what is happening in bash?

In the first command, the programs after the pipe (i.e. read) run in a subshell. Although it correctly assigns, these assignments are lost when the command completes and the subshell exits.

There are a few ways around it:

a. Braces

echo "hello world" | {
  read first second
  echo $second $first
}

b. Heredoc

read first second <<< "hello world"
echo $second $first

Why does this work? Simply because we don't need to resort to a pipe to get the string input into the read command so no subprocess is created.