Redirecting Input with <

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 58 of 205

The < operator connects a file to the standard input of a command. Instead of waiting for you to type, or for another command to send data, the command reads its input straight from the file. It is the mirror image of >: where > changes where standard output goes, < changes where standard input comes from.

The Basic Syntax

command < file

The shell opens the file for reading and attaches it to file descriptor 0, standard input, before the command starts. The command then reads from standard input in its usual way and has no idea that a file is on the other end.

The examples in this lesson use two small files:

printf 'pear\napple\nfig\napple\n' > fruits.txt
printf 'alpha beta\ngamma delta\n' > words.txt

How It Works

When Bash sees < fruits.txt it performs these steps:

  1. It opens fruits.txt in read-only mode. The file is never modified or emptied.
  2. It makes file descriptor 0 of the new process refer to that open file.
  3. It starts the command, which reads from standard input.

If the file cannot be opened, the command does not run at all. The file name is removed from the command line before the program starts, so the program does not receive it as an argument.

Argument or Redirection?

For many commands there are two ways to read a file: pass its name as an argument, or redirect it to standard input. Compare them with wc:

wc -l fruits.txt
wc -l < fruits.txt

Output:

4 fruits.txt
4

The count is the same, but the first form prints the file name and the second does not. In the first form, wc receives the name, opens the file itself and can report the name. In the second form, wc only sees an anonymous stream of lines, so it has no name to print. This difference is useful when you want just the number, for example when you store it in a variable:

lines=$(wc -l < fruits.txt)
echo "The file has $lines lines"

Output:

The file has 4 lines

Commands That Only Read Standard Input

Some commands do not take a file name at all and read only standard input. The command tr, which translates or deletes characters, is one of them:

tr 'a-z' 'A-Z' < words.txt

Output:

ALPHA BETA
GAMMA DELTA

Here < is the only way to hand a file to tr, because tr never accepts file names; its arguments are the character sets. Another example removes characters:

tr -d 'aeiou' < words.txt

Output:

lph bt
gmm dlt

The calculator bc reads its expressions from standard input too, so a file of expressions can be fed to it:

echo "2+3" > expr.txt
bc < expr.txt

Output:

5

Using Redirection with sort, grep and head

Commands that accept both forms work with < as well:

sort < fruits.txt

Output:

apple
apple
fig
pear

The grep command shows the naming difference again. With a file argument and the -H option, it prints the file name. When reading from standard input, it uses the label (standard input):

grep apple < fruits.txt
grep -H apple < fruits.txt

Output:

apple
apple
(standard input):apple
(standard input):apple

Placing the Redirection First

As with output redirection, the position of < on the command line does not matter to Bash. This form puts the input at the beginning, so the line reads like "from this file, take the first two lines":

< fruits.txt head -n 2

Output:

pear
apple

Most people write the redirection after the command, but you will see the other style in scripts and in pipelines that start with a file.

Input and Output Together

You can use < and > in the same command. The command reads from one file and writes to another:

sort < fruits.txt > sorted.txt
cat sorted.txt

Output:

apple
apple
fig
pear

Be careful not to name the same file on both sides. Bash empties the output file before the command starts, so the input file would be empty by the time the command reads it:

sort < fruits.txt > fruits.txt

This command destroys the contents of fruits.txt. The previous lesson shows the safe pattern of writing to a temporary file and then moving it.

When the Input File Is Wrong

If the file does not exist, Bash reports the error itself and does not start the command:

cat < nothere.txt
echo "status: $?"

Output:

bash: nothere.txt: No such file or directory
status: 1

Notice that the message begins with bash:, not with cat:. The error came from the shell, not from the program, which is how you can tell a redirection problem from a command problem. If the name belongs to a directory, the shell opens it successfully but the command fails when it tries to read:

mkdir adir
cat < adir

Output:

cat: -: Is a directory

The - in the message is the name cat gives to standard input.

Reading Lines with read

The built-in read command reads one line from standard input. With a redirection, it reads from the file:

read -r first < fruits.txt
echo "first=$first"

Output:

first=pear

Each < fruits.txt opens the file again from the beginning. A second command therefore starts over:

read -r again < fruits.txt
echo "again=$again"

Output:

again=pear

It printed pear again, not apple, because it was a new redirection. To read the file line by line, you need one redirection that stays open for the whole loop, which is the next topic.

Reading a File in a while Loop

A while loop can take its input from a file by placing the redirection after done:

while IFS= read -r line; do
  echo "got: $line"
done < fruits.txt

Output:

got: pear
got: apple
got: fig
got: apple

The file is opened once, when the loop starts, and every read continues where the previous one stopped. The parts IFS= and -r keep leading spaces and backslashes in each line unchanged. A later lesson on reading files line by line explains them in depth.

Because the loop runs in the current shell, variables set inside it are still available afterward:

count=0
while read -r line; do count=$((count+1)); done < fruits.txt
echo "count=$count"

Output:

count=4

If you feed the loop with a pipe instead, the loop runs in a subshell, which is a separate copy of the shell, and the counter is lost:

count=0
cat fruits.txt | while read -r line; do count=$((count+1)); done
echo "count=$count"

Output:

count=0

This is one reason < file is often better than cat file | for loops.

Commands Inside a Loop Share the Input

Inside a loop that reads from a file, any command that also reads standard input shares the same open file and takes lines away from the loop. In this example, head -n 1 consumes one line on every pass:

printf 'a\nb\nc\n' > three.txt
while read -r line; do
  echo "outer: $line"
  head -n 1 > /dev/null
done < three.txt

Output:

outer: a
outer: c

The line b was swallowed by head. The fix is to give the loop its own file descriptor and read from it with <&3:

while read -r line <&3; do
  echo "outer: $line"
  head -n 1 < /dev/null
done 3< three.txt

Output:

outer: a
outer: b
outer: c

Here 3< three.txt opens the file on descriptor 3 for the whole loop, read ... <&3 takes each line from it, and the inner command keeps using the real standard input, so nothing is lost. Descriptors above 2 are free for your own use. A later lesson on safely looping through command output uses this idea again.

Naming Descriptor 0

The short form < is the same as 0<, where 0 is the descriptor for standard input:

wc -l 0< fruits.txt

Output:

4

Most scripts leave the 0 out. It is useful to know when you read examples that spell it out, and for saving and restoring descriptors later.

Scripts That Read Standard Input

A script reads standard input in the same way as any other command, so you can feed it a file. This script reads two lines:

read -r a
read -r b
echo "a=$a b=$b"

Saved as readtwo.sh and run with a file on standard input:

bash readtwo.sh < words.txt

Output:

a=alpha beta b=gamma delta

Each read took the next line from the same stream. Run in a terminal, the same script would wait for you to type two lines.

Redirecting for the Rest of the Script

The built-in exec with only a redirection changes the streams for the current shell instead of for one command. This example does it inside parentheses so that it only affects a subshell:

( exec < fruits.txt; read -r x; read -r y; echo "x=$x y=$y" )

Output:

x=pear y=apple

After exec < fruits.txt, every command in the subshell reads from the file, and both read commands continued through it. Used at the top of a script, exec < file makes the whole script read from that file. Keep this form for later: it is powerful, but harder to follow than a loop with done < file.

The < operator needs an existing file. Two related operators supply the text directly in the script, without a separate file. Here documents, written <<, and here strings, written <<<, each have their own lesson. Pipes, written |, connect the output of another command to the input, and also have their own lesson.

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 Redirecting Input with < and get answers drawn from it.

Signed-in readers only.