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.
Bash uses three standard I/O streams:
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
To use a file as input, employ the <
operator:
sort < unsorted_list.txt
This command sorts the contents of unsorted_list.txt
.
Redirect error messages using 2>
:
ls non_existent_directory 2> error.log
This captures error messages in error.log
.
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
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.
/dev/null
to suppress it>
>>
for logs to append rather than overwriteMastering 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.