In Linux and other Unix-like systems, you can use standard redirection to control the input and output of commands. Here’s a brief overview of how to use these redirections:
- Standard Output (stdout) Redirection: The standard output (usually the terminal) can be redirected to a file. This means that instead of seeing the output on your screen, it’ll be saved to a file.
- Overwrite a file:
command > filename
This will overwritethe filename
with the output ofthe command
. - Append to a file:
bash command >> filename
This will append the output ofcommand
tofilename
without overwriting its current content.
- Standard Error (stderr) Redirection: Sometimes commands generate errors, and these errors are sent to stderr.
- Overwrite a file:
command 2> errorfile
This will overwriteerrorfile
with the error messages fromcommand
. - Append to a file:
bash command 2>> errorfile
This will append the error messages fromcommand
toerrorfile
.
- Redirect Both stdout and stderr: If you want to redirect both standard output and standard error to the same file:
- Overwrite a file:
command > filename 2>&1
- Append to a file:
command >> filename 2>&1
The2>&1
syntax tells the shell to redirect the standard error (file descriptor 2) to the same location as the standard output (file descriptor 1).
- Pipes (
|
): The pipe operator allows you to use the output of one command as the input of another. This is very useful for chaining commands together.
command1 | command2
The output of command1
is used as the input to command2
.
- Input Redirection: You can also redirect the input of a command:
command < inputfile
This will use inputfile
as the input to command
.
- Discarding Output: If you want to discard the output (or errors) of a command, you can redirect it to the special file
/dev/null
:
command > /dev/null 2>&1
This discards both standard output and standard error.
NOTE: the order of redirections matters. For example,
command > filename 2>&1
is not the same ascommand 2>&1 > filename
. The first command redirects both the standard output (stdout) and standard error (stderr) to a file named “filename”. The second command redirects the standard output to the “filename” file, while keeping the standard error in its original location, typically the terminal.