Bash Input/Output Redirection
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →Input/output redirection is a fundamental concept in Bash that allows you to control the flow of data between commands and files. It's an essential skill for efficient shell scripting and command-line operations.
Understanding I/O Streams
Bash uses three standard I/O streams:
- stdin (0): Standard input
- stdout (1): Standard output
- stderr (2): Standard error
Output Redirection
To redirect output to a file, use the > operator:
echo "Hello, World!" > output.txt
This command writes the output to output.txt, overwriting its contents. To append instead, use >>:
echo "Appended line" >> output.txt
Input Redirection
To use a file as input, employ the < operator:
sort < unsorted_list.txt
This command sorts the contents of unsorted_list.txt.
Error Redirection
Redirect error messages using 2>:
ls non_existent_directory 2> error.log
This captures error messages in error.log.
Combining Redirections
You can redirect both output and error streams:
command > output.txt 2> error.log
To send both streams to the same file:
command &> combined_output.log
Here Documents
For multi-line input, use here documents:
cat << EOF > multiline.txt
Line 1
Line 2
Line 3
EOF
This creates a file with three lines of text. Here documents are particularly useful in Bash script structures.
Practical Applications
- Logging: Redirect output to log files for later analysis
- Silent execution: Redirect output to
/dev/nullto suppress it - Input automation: Use input redirection to feed commands with prepared data
Best Practices
- Always consider potential file overwriting when using
> - Use
>>for logs to append rather than overwrite - Redirect errors to separate files for easier debugging
- Combine redirection with Bash pipes for complex data processing
Mastering input/output redirection enhances your ability to manipulate data streams effectively in Bash. It's a crucial skill for both everyday command-line use and advanced Bash scripting.