Post

redirections.bin

redirections.bin

I/O redirection in Linux is a mechanism that allows you to change the destination of input and output for commands. by default, linux commands read from the standard input (stdin) and write to the standard output (stdout) and standard error (stderr). Redirection enables you to direct these streams.

Basics of I/O Redirection

  1. stdin, stdout, and stderr

    • Standard Input (stdin): This is the default source of input for commands, typically the keyboard.
    • Standard Output (stdout): This is the default destination for command output, typically the terminal.
    • Standard Error (stderr): This is the default destination for error messages, also typically the terminal.
  2. Operators

    • >: Redirects stdout to a file, overwriting the file if it already exists.
    • >>: Redirects stdout to a file, appending to the file if it already exists.
    • <: Redirects stdin from a file.
    • 2>: Redirects stderr to a file, overwriting the file if it already exists.
    • 2>>: Redirects stderr to a file, appending to the file if it already exists.
    • &>: Redirects both stdout and stderr to a file.

Some Example Techniques

Pipes (|): In Unix Like systems pipes allow you to use the output of one command as the input to another.

1
2
 esrie@mint:~$ ls -l | grep Hello
-rw-rw-r--  1 esrie esrie    0 Sep 13 21:37 Hello

File Descriptor Redirection

  • exec: You can use exec to redirect file descriptors. to redirect both stdout and stderr in a script. This command saves the current stdout and stderr to file descriptors 3 and 4. later you can restore em if needed.
    1
    
    exec 3>&1 4>&2
    

Redirection Examples

Redirect Output and Errors Simultaneously.

Imagine you want to run a command and log both its stdout and stderr into different files while also viewing the output on the term you can achive this using tee command combined with redirection.

1
com > >(tee output.log) 2> >(tee error.log >&2)

Redirect Outputs with Conditional Execution

1
com > output.log 2> error.log && echo "com succeeded" >> output.log || echo "com failed" >> error.log`

These examples should give you some understanding of how to use redirections with common commands in linux.

I also recommend reading this excellent blog post about pipes,forks, and dups by Rozmichelle. which provides an excellent in-depth understanding about i/o dataflow.

This post is licensed under CC BY 4.0 by the author.

Trending Tags