0
0
Linux CLIscripting~5 mins

stdin redirection (<) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want a command to read input from a file instead of typing it manually. Stdin redirection with the < symbol lets you do that by sending the file content as input to the command.
When you want to provide a list of items stored in a file to a command that reads from standard input.
When you want to test a program that reads input interactively by giving it input from a file instead.
When you want to automate feeding data to a command without typing it each time.
When you want to process a file line by line using a command that reads from stdin.
When you want to combine commands that expect input from the keyboard with file data.
Commands
This command uses stdin redirection to send the content of example.txt to the cat command, which then prints it to the terminal.
Terminal
cat < example.txt
Expected OutputExpected
Hello, this is a sample file. It has multiple lines. This is the third line.
This command counts the number of lines in example.txt by redirecting the file content as input to wc with the -l flag.
Terminal
wc -l < example.txt
Expected OutputExpected
3
-l - Counts the number of lines in the input
Key Concept

If you remember nothing else from this pattern, remember: the < symbol sends a file's content as input to a command instead of typing it manually.

Common Mistakes
Using > instead of < for input redirection
The > symbol redirects output to a file, not input from a file, so the command won't get the intended input.
Use < to redirect input from a file to a command.
Trying to redirect input from a non-existent file
The command will fail because the file does not exist and there is no input to read.
Make sure the file exists and has the data you want to provide before redirecting.
Summary
Use < to send a file's content as input to a command that reads from standard input.
This lets you automate commands that normally require typing input manually.
Always check the file exists and contains the data you want before redirecting.