
Input/Output (I/O) redirection is a fundamental concept in Linux that allows you to control where the input and output of commands are directed. Instead of relying on the default standard input (stdin), standard output (stdout), and standard error (stderr), you can redirect them to files or other commands.
Understanding I/O Redirection:
> (Output Redirection): Redirects the standard output of a command to a file, overwriting the file if it already exists.
Example: ls -l > file_list.txt (saves the output of ls -l to file_list.txt)
>> (Append Output Redirection): Redirects the standard output of a command to a file, appending to the file if it already exists.
Example: echo "New entry" >> log.txt (adds "New entry" to the end of log.txt)
< (Input Redirection): Redirects the standard input of a command from a file.
Example: sort < numbers.txt (sorts the contents of numbers.txt)
2> (Error Redirection): Redirects the standard error of a command to a file.
Example: command 2> error.log (redirects all errors to error.log)
&> (Redirect both standard output and standard error): Redirects both standard output and standard error to a file.
Example: command &> output.log (redirects all output and errors to output.log)
Practical Examples:
Saving Output to a File:
$ ls -l > directory_contents.txt
Appending to a Log File:
$ date >> system_log.txt
Using a File as Input:
$ wc -l < word_list.txt (counts the lines in word_list.txt)
Redirecting Errors:
$ find /nonexistent 2> error_log.txt
Redirecting both output and errors:
$ command &> all_output.log
Practice Session 1: With Example Commands
Create a file named "data.txt" with some lines of text:
$ echo "Line 1" > data.txt
$ echo "Line 2" >> data.txt
$ echo "Line 3" >> data.txt
Redirect the output of cat data.txt to a new file named "output.txt":
$ cat data.txt > output.txt
Append the current date and time to "output.txt":
$ date >> output.txt
Use sort to sort the lines in "data.txt" and redirect the output to "sorted.txt":
$ sort < data.txt > sorted.txt
Attempt to list a nonexistent directory and redirect the error to "error.log":
$ ls nonexistent_dir 2> error.log
Run a command that has both standard output and standard error, and redirect everything to all_logs.txt:
$ find /nonexistent /etc &> all_logs.txt
Practice Session 2: Without Example Commands
Create a file named "words.txt" with a list of words, one word per line.
Use the grep command to search for a specific word in "words.txt" and redirect the matching lines to a file named "matches.txt".
Append the output of the who command to "matches.txt".
Use the wc command to count the number of words in "words.txt" and redirect the output to "word_count.txt".
Run a command that is known to create an error, and redirect only the error output into error_output.txt.
Run a command that has both normal output and errors, and redirect everything to a single file named combined_output.txt.
Sort the words in word.txt and save the sorted output to sorted_words.txt
Comments