Standard input (stdin) is one of the three standard data streams in Linux, representing the default source from which programs read input data.
It's assigned file descriptor 0 and typically connects to the keyboard by default.
Understanding stdin
When you run a command, it expects input from somewhere. By default, this "somewhere" is your keyboard - this is stdin. Programs read data from stdin character by character or line by line, waiting for user input.
Basic stdin Examples
Interactive Command Input
cat
# After pressing Enter, cat waits for keyboard input
Hello World
# Press Ctrl+D to end input
The cat command without arguments reads from stdin and echoes to stdout.
Reading User Input in Scripts
read name
echo "Hello, $name"
# Program waits for user to type their name
Redirecting stdin
From Files (<)
sort < unsorted_data.txt
# sort reads from file instead of keyboard
From Here Documents (<<)
mysql -u root -p << EOF
USE database_name;
SELECT * FROM users;
EOF
# SQL commands are fed to mysql via stdin
From Here Strings (<<<)
grep "error" <<< "This is an error message"
# String is passed directly as input
Pipes and stdin
ls -l | grep ".txt"
# ls output becomes grep's stdin
Multiple Command Chain
ps aux | grep firefox | awk '{print $2}' | xargs kill
# Each command receives previous command's output as stdin
Practical Applications
Processing Large Files
while read line; do
echo "Processing: $line"
done < large_file.txt
Interactive Menu Systems
echo "Choose option (1-3):"
read choice
case $choice in
1) echo "Option 1 selected";;
2) echo "Option 2 selected";;
*) echo "Invalid choice";;
esac
Filtering Data
# Filter log entries
grep "ERROR" < /var/log/application.log > errors_only.log
stdin in Programming
Programs can check if stdin is connected to a terminal or redirected:
if [ -t 0 ]; then
echo "Reading from terminal"
else
echo "Reading from file/pipe"
fi
Understanding stdin is crucial for creating interactive scripts, processing data streams, and building efficient command pipelines in Linux environments.