Bash: Here String (`<<<`)
The here string operator provides a simple and clean way to redirect a string's content into a command's standard input (stdin). It is an alternative to pipes or temporary files, especially for short, single-line or multi-line strings.
Basic Usage
# A here string sends "Hello World!" to the cat command's stdin
cat <<< "Hello World!"
# Result:
# Hello World!
The <<< operator takes the string on its right and feeds it directly to the command on its left. The command then processes this string as if it were read from a file or from the keyboard.
Here String with Variables
Here strings are most commonly used to pass the content of a variable to a command, especially when the variable contains newlines.
my_list="first item
second item
third item"
# The while loop reads from the here string line by line
while read line; do
echo "Processing line: $line"
done <<< "$my_list"
# Result:
# Processing line: first item
# Processing line: second item
# Processing line: third item
This pattern is a very common and efficient way to iterate over multi-line data without needing to create a temporary file.
Here String vs. Pipe (|)
While both `<<<` and `|` can be used to pass data to a command, a here string is generally more efficient for simple cases. A pipe creates a subshell, which can affect variable scope. A here string does not, keeping the loop's context within the current shell.
# Using a pipe creates a subshell, so the counter variable is lost
counter=0
echo "apple" | while read fruit; do
counter=$((counter+1))
done
echo "Counter value: $counter" # Result will be 0
# Using a here string keeps the loop in the current shell
counter=0
while read fruit; do
counter=$((counter+1))
done <<< "apple"
echo "Counter value: $counter" # Result will be 1
The here string is often the preferred method for simple data processing within loops because it does not create a subshell, preserving the state of variables modified inside the loop.