Skip to content

Latest commit

 

History

History
84 lines (51 loc) · 2.48 KB

01.Redirecting_standard_input_and_output.md

File metadata and controls

84 lines (51 loc) · 2.48 KB

Input/Output Redirection in Linux Scripting

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.

Output Redirection

Redirecting Standard Output (stdout)

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

Redirecting Standard Error (stderr)

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

Input Redirection

Redirecting Standard Input (stdin)

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.

Using a Here Document

A Here Document allows you to provide input directly within the script:

command <<EOF
This is
a Here Document
EOF

Combining Input and Output Redirection

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

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.

Conclusion

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.