Linux I/O redirection examples

February 15, 2016


I/O redirections are one of the prettiest things we have in linux (IMO!) Following are commands and their usage.

command_output >> file   Redirects stdout to a file. Creates the file if not present, otherwise appends.

> filename   Truncates the file to zero length. If file is not present, creates zero-length file (same effect as touch).

1>filename   Redirects stdout to the file “filename”.

1>>filename   Redirects and appends stdout to file “filename”.

2>filename   Redirects stderr to file “filename”.

2>>filename   Redirects and appends stderr to file “filename”.

&>filename   Redirects both stdout and stderr to file “filename”.

2>&1   Redirects stderr to stdout. Error messages get sent to same place as standard output.


Some quality explanation now ;) Take the example of this command:
cmd >> file.log 2>&1
This command will redirect all the output of command(cmd) into file.log.
2 refers to Second file descriptor of the process i.e., stderr
> refers to redirection
&1 means that the target of redirection would be same as 1 i.e, first descriptor i.e, stdout.

Thanks!


Tags: Hacker Programming Linux


blog comments powered by Disqus