Bash

๐Ÿ”ƒ Bash I/O Redirection

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.


๐Ÿ”ข File Descriptors

FD Stream
0 stdin (input)
1 stdout (output)
2 stderr (error)

๐Ÿ“ค Output Redirection

Overwrite output:

echo "Hello" > output.txt

Append output:

echo "More text" >> output.txt

๐Ÿ“ฅ Input Redirection

Use input from a file:

cat < input.txt

Can be used in loops:

while read line; do
  echo $line
done < file.txt

โŒ Redirecting Errors

Redirect stderr to a file:

ls /invalid/path 2> error.log

Redirect stdout and stderr to different files:

command > out.log 2> err.log

Combine both to same file:

command > all.log 2>&1

๐Ÿ”„ Use tee to Split Output

Write to file and show on terminal:

ls -l | tee output.log

Append to file:

ls -l | tee -a output.log

๐Ÿงช Examples

Log everything (stdout + stderr):

myscript.sh > script.log 2>&1

Silent execution (discard output):

command > /dev/null 2>&1

๐Ÿงฒ Process Substitution

Use command output as a file:

diff <(ls dir1) <(ls dir2)

This lets you treat the result of a command as a temporary file.


๐Ÿงฌ Advanced File Descriptors

Open a new file descriptor:

exec 3> file.txt
echo "Hello" >&3
exec 3>&-    # Close it

Read from descriptor:

exec 4< input.txt
read line <&4
exec 4<&-

๐Ÿ“Œ Best Practices

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

๐Ÿ“š References


๐Ÿ“ File: advance/io-redirection.md
Author: Kashif Alam