I/O and Redirection
I/O stands for input/output. Redirection allows us to direct input and output functions to specific files or folders using special commands or characters.
Standard Streams
Standard Input (stdin): This is the default source of input for a command, usually the keyboard. It’s represented by the number
0
.Standard Output (stdout): This is the default destination for output from a command, usually the terminal screen. It’s represented by the number
1
.Standard Error (stderr): This is the default destination for error messages from a command, also usually the terminal screen. It’s represented by the number
2
.
Types of Redirection
1. Overwrite Redirection:
Overwrite redirection is useful when you want to save the output of a command to a file, replacing the file's existing content entirely.
“>” standard output – Redirects stdout to a file, overwriting the file if it exists
command > file.txt
ls > directory_list.txt
#lists the contents of the current directory and saves the output to directory_list.txt
“<” standard input – Redirects stdin from a file
command < file.txt
wc < hello.txt
#command counts the lines, words, and characters in hello.txt
2. Append Redirection:
Append the output to the file without overwriting the existing data.
“>>” standard output – Redirects stdout to a file, appending to the file if it exists
cat >> file.txt
echo "Hello again!" >> hello.txt
#adds “Hello again!” to the end of hello.txt
“<<” standard input
3. Merge Redirection:
Error Redirection – Save error messages to a file
2>” re-directs the error output to a file named “error.txt”
error message generated by “2” gets merged with the current output “1“.
Redirecting Both stdout and stderr
Overwrite a file with both outputs
Append both outputs to a file