Here Strings with <<<

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 64 of 205

A here string gives a command a single string as its standard input. It is written with three less-than signs, <<<, followed by the text. It is a Bash feature (also found in Zsh and a few other shells) that replaces the common but clumsy pattern echo "text" | command with a form that starts no extra process and does not run the receiving command in a subshell.

Understanding the Concept

Lesson 63 showed that a here document sends a block of lines to a command. A here string is the one-line version. You do not need a delimiter or a closing marker: the word after <<< is the entire input. The shell expands it, adds a newline at the end, and attaches it to the standard input of the command.

Syntax

command <<< "string"

The string is usually quoted. A variable can stand in for the string: command <<< "$variable".

Basic Example

cat <<< "hello"
tr 'a-z' 'A-Z' <<< "hello"

Output:

hello
HELLO

Understanding the Example

The first command printed the string, because cat copies its standard input to its standard output. The second one gave the same string to tr, which converted lowercase letters to uppercase. In both cases the string was the input of the command, as if you had typed it and pressed Enter.

The word after <<< is a single item. If it contains spaces and is not quoted, only the first word becomes the input and the rest become ordinary arguments:

cat <<< hello world

Output:

hello
cat: world: No such file or directory

The string hello went to standard input, but world was passed to cat as a file name. Quote the string to keep it together.

The Newline at the End

A here string always adds a newline to the end of the text. You can see the extra character by comparing it with printf, which adds nothing:

od -c <<< "hi"
printf 'hi' | od -c

Output:

0000000   h   i  \n
0000003
0000000   h   i
0000002

The here string delivered three bytes, h, i and a newline, while printf delivered only two. Most text tools expect lines to end with a newline, so the extra byte is usually helpful. It does matter for commands that count characters. An empty variable still produces one empty line:

empty=""
wc -l <<< "$empty"
wc -c <<< "$empty"

Output:

1
1

Expansion in a Here String

The shell expands the string before the command sees it. Variables, command substitutions and arithmetic expansions work, and quotes control them in the usual way:

name="Ana Maria"
wc -w <<< "$name"
grep -o 'Maria' <<< "$name"

Output:

2
Maria

Single quotes switch expansion off, and double quotes allow it:

cat <<< 'single $no expansion'
cat <<< "double $name expansion"

Output:

single $no expansion
double Ana Maria expansion

A command substitution works the same way. This counts the characters in the current year, plus the newline that the here string adds:

wc -c <<< "$(date +%Y)"

Output:

5

A year has four digits. The fifth character is the newline.

Word Splitting Does Not Apply

One difference from command arguments is worth knowing: the shell does not split an unquoted variable in a here string into separate words. The spacing is preserved:

v="a   b    c"
cat <<< $v
cat <<< "$v"

Output:

a   b    c
a   b    c

Both forms printed the same text. Even so, quoting is the clearer habit, because it makes the intention obvious and keeps the line safe if you later move it into an argument list.

Reading Values into Variables

The most common use of a here string is with read. The read command splits a line into fields and stores them in variables:

read -r first second rest <<< "one two three four"
echo "first=$first second=$second rest=$rest"

Output:

first=one second=two rest=three four

The last variable receives everything that is left, which is why rest holds two words. Now compare that with the pipe form from lesson 61:

read -r a b <<< "x y"
echo "a=$a b=$b"
echo "x y" | read -r c d
echo "c='${c:-}' d='${d:-}'"

Output:

a=x b=y
c='' d=''

With a here string, read runs in the current shell, so its variables stay available. With a pipe, read runs in a subshell, and the assignments are lost. This is the main reason to prefer <<< over echo ... | when the receiving command needs to change your variables.

The variable IFS, the internal field separator, chooses the characters that separate fields. Setting it only for the read command splits on that character:

IFS=: read -r user pw uid <<< "root:x:0:0"
echo "user=$user pw=$pw uid=$uid"

Output:

user=root pw=x uid=0:0

The third variable uid received the whole remainder, 0:0, because only three variables were supplied. The IFS=: assignment applies to that single read command and does not change the shell's IFS afterwards.

A date can be taken apart in the same way:

IFS=- read -r y m d <<< "2026-11-21"
echo "y=$y m=$m d=$d"

Output:

y=2026 m=11 d=21

Splitting a String into an Array

The read command can fill an array with its -a option, which is useful for comma-separated values:

IFS=, read -r -a parts <<< "red,green,blue"
echo "count=${#parts[@]} second=${parts[1]}"

Output:

count=3 second=green

The array parts has three elements numbered from 0, so the second element, at index 1, is green. Lessons 97 to 105 cover arrays in detail.

Leading and Trailing Spaces

By default, read removes leading and trailing whitespace from the line, because those characters are part of IFS. Emptying IFS for the command keeps them:

read -r t <<< "   spaced out   "
printf '[%s]\n' "$t"
IFS= read -r t <<< "   spaced out   "
printf '[%s]\n' "$t"

Output:

[spaced out]
[   spaced out   ]

When reading lines in loops, the form IFS= read -r line is the standard way to keep each line exactly as it is. A later lesson on reading files line by line (114) builds on it.

Looping Over the Lines of a Variable

A while read loop can read from a here string. Because the loop is not part of a pipeline, its variables survive:

list=$'alpha\nbeta\ngamma'
n=0
while IFS= read -r item; do n=$((n+1)); echo "$n: $item"; done <<< "$list"
echo "n after loop: $n"

Output:

1: alpha
2: beta
3: gamma
n after loop: 3

The $'...' form creates a string with real newline characters. The here string passed all three lines to the loop on standard input, and after the loop the counter n still held 3.

Feeding Text to Common Commands

Here strings work with any command that reads standard input. These examples show a few typical uses:

data=$'b\na\nc'
sort <<< "$data"
a
b
c
text="error: disk full"
if grep -q 'disk' <<< "$text"; then echo "match"; fi
match
bc <<< "2 + 3 * 4"
bc <<< "scale=2; 10 / 3"
14
3.33
cut -d' ' -f2 <<< "one two three"
awk '{print $2}' <<< "alpha beta gamma"
sed 's/cat/dog/' <<< "the cat sat"
two
beta
the dog sat

The calculator bc is not always installed on minimal systems, so check for it before depending on it in a script.

The same technique handles a whole line of words. This converts a space-separated string into one word per line and removes duplicates:

tr ' ' '\n' <<< "b a b c a" | sort -u
a
b
c

A here string can also sit inside a test, as in this check on the number of words:

if [[ $(wc -w <<< "a b c") -eq 3 ]]; then echo "three words"; fi
three words

Portability

Here strings are not part of the POSIX shell standard. Dash, the shell that sh points to on Debian and Ubuntu, rejects them with a syntax error:

dash -c 'cat <<< "hi"'

Output:

dash: 1: Syntax error: redirection unexpected

In a script that must run under sh, use a pipe, printf '%s\n' "$text" | command, or a here document. In scripts that start with #!/usr/bin/env bash, here strings are safe to use.

The next lesson, on command lists, shows how to combine commands with ;, && and ||.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Here Strings with <<< and get answers drawn from it.

Signed-in readers only.