Bash allows you to redirect standard input, output, and errors to/from files, devices, and other commands. This is powerful for logging, error handling, and automation.
FD | Stream |
---|---|
0 |
stdin (input) |
1 |
stdout (output) |
2 |
stderr (error) |
echo "Hello" > output.txt
echo "More text" >> output.txt
Use input from a file:
cat < input.txt
Can be used in loops:
while read line; do
echo $line
done < file.txt
stderr
to a file:ls /invalid/path 2> error.log
stdout
and stderr
to different files:command > out.log 2> err.log
command > all.log 2>&1
tee
to Split OutputWrite to file and show on terminal:
ls -l | tee output.log
Append to file:
ls -l | tee -a output.log
myscript.sh > script.log 2>&1
command > /dev/null 2>&1
Use command output as a file:
diff <(ls dir1) <(ls dir2)
This lets you treat the result of a command as a temporary file.
exec 3> file.txt
echo "Hello" >&3
exec 3>&- # Close it
exec 4< input.txt
read line <&4
exec 4<&-
Tip | Reason |
---|---|
Use 2>&1 for error and output logs |
Easier debugging |
Use tee to log and view output |
Great for scripts |
Redirect to /dev/null for silence |
For crons and clean logs |
Quote filenames in redirections | Avoid word splitting |
๐ File:
advance/io-redirection.md
Author: Kashif Alam