In Bash, input/output (I/O) redirection allows you to control where the input comes from and where the output goes. It allows you to redirect standard input (stdin), standard output (stdout), and standard error (stderr) to different sources or destinations. Here are some common I/O redirection operators in Bash:
- Standard Input Redirection:
< file
: Redirects stdin to read from a file instead of the terminal. For example:
command < input.txt
2. Standard Output Redirection:
> file
: Redirects stdout to write to a file, overwriting its contents if it exists, or creating a new file if it doesn’t. For example:
command > output.txt
>> file
: Redirects stdout to append to a file, preserving its existing contents or creating a new file if it doesn’t exist. For example:
command >> output.txt
3. Standard Error Redirection:
2> file
: Redirects stderr to write to a file. For example:
command 2> error.log
4. Redirecting both stdout and stderr:
&> file
or> file 2>&1
: Redirects both stdout and stderr to write to a file. For example:
command &> output.log
&>> file
or >> file 2>&1
: Redirects both stdout and stderr to append to a file. For example:
5. Discarding Output:
> /dev/null
: Redirects output to the special device file/dev/null
, effectively discarding it. For example:
command > /dev/null
6. Here Documents: Here documents allow you to redirect a block of text as input to a command. The syntax is as follows:
command << EOF
text
EOF
The <<
operator is followed by a delimiter (in this case, EOF
) that marks the start and end of the block of text.
These redirection operators provide flexibility in directing input and output streams in Bash. By utilizing them, you can redirect output to files, append to existing files, capture errors, discard output, and customize the flow of data in your Bash scripts.