Input/Output (I/O) redirection in Linux scripting allows you to control where data comes from and where it goes, enhancing the flexibility of your scripts. This tutorial will guide you through the usage of input and output redirection in a Linux environment.
Standard Output is the default channel for a command's output. You can redirect it to a file using the >
operator:
command > output.txt
This will overwrite the content of output.txt
with the output of the command
. To append the output to the file without overwriting, use >>
:
command >> output.txt
Standard Error is the default channel for error messages. You can redirect it similarly to Standard Output:
command 2> error.log
This redirects error messages from command
to error.log
. To redirect both Standard Output and Standard Error to the same file, you can use:
command > output_and_error.log 2>&1
Standard Input is the default channel for a command's input. You can redirect it from a file using the <
operator:
command < input.txt
This will take the content of input.txt
and use it as input for command
.
A Here Document allows you to provide input directly within the script:
command <<EOF
This is
a Here Document
EOF
You can combine input and output redirection in a single command. For example, to take input from input.txt
and write both output and errors to output.log
:
command < input.txt > output.log 2>&1
Pipes (|
) enable you to send the output of one command as the input to another:
command1 | command2
This passes the output of command1
as input to command2
.
Understanding input/output redirection is crucial for efficient Linux scripting. Whether you are managing files, handling command output, or chaining commands together, the ability to control where data flows enhances the versatility of your scripts. Experiment with these redirection techniques to master their usage in your Linux scripts.