Bash by Example: Here Strings
Passing a single string to stdin using the <<< here string operator for feeding literal strings or variable content to commands, understanding how here strings differ from here documents by providing single-line input, using here strings with commands that read from stdin, avoiding unnecessary echo piping, and implementing clean command input patterns.
Code
#!/bin/bash
text="Hello World"
# 1. Basic Usage
# Equivalent to: echo "$text" | cat
cat <<< "$text"
# 2. String Manipulation with tools
# Convert to uppercase using tr
tr 'a-z' 'A-Z' <<< "make me uppercase"
# 3. Reading into read
# Parse a string into variables
IFS=':' read -r user pass uid gid <<< "root:x:0:0"
echo "User: $user, UID: $uid"
# 4. Search in a variable
if grep -q "World" <<< "$text"; then
echo "Found 'World' in the variable."
fi
# 5. Calculator (bc)
result=$(bc <<< "scale=2; 10 / 3")
echo "10 / 3 = $result"Explanation
A "Here String" is a simplified form of the Here Document, introduced in Bash 3.0. The syntax <<< "string" feeds the string directly into the standard input of the command. It is syntactically cleaner and more efficient than piping echo "string" | command because it doesn't require forking a subshell for the echo command.
This feature is widely used for one-liners and quick string processing. For instance, if you have a variable and you want to search inside it using grep, or transform it using sed or awk, a Here String is the most elegant way to pass that variable's content to the tool.
It is also the standard way to feed input to the bc (Basic Calculator) utility for floating-point arithmetic, which Bash doesn't support natively. By sending the math expression as a Here String, you can capture the result easily.
Code Breakdown
cat <<< "$text". The shell handles the redirection internally. It's a cleaner alternative to echo "$text" | cat.read with a Here String is a powerful parsing technique. We set the delimiter IFS=':' and feed the string "root:x:0:0" directly into the variables.bc reads from stdin. We pass the calculation string to it, and capture the output into result.
