Linux I/O Redirection
Redirection with Files
Let's get started with a few simple examples of redirection:
command > filename # Redirect command's output to a new or overwritten file
command < filename # Use filename's contents as standard input for commandThe first command would overwrite an existing file. So what if we want to only append command's output to a file?
command >> filename # Append command's output to filenameIf you're a C++ programmer, you can remember the difference between this and the first output redirection command by recalling that C++ uses the >> operator to add to a stream, not replace it.
Speaking of C++, it uses three main streams:
stdin: 0
stdout: 1
stderr: 2
If we want to save standard error to a file, we can:
command 2> error_outputWe could do the same with standard output, or even redirect standard error to standard output:
command 2>&1And that's the basics of using I/O redirection with files. What if we want to send the output of one command to another as it's input? Linux allows us to do this using pipes.
Pipes
We can pipe the output of one command into the input of another:
first_command | second_commandWe could even create a named pipe that delivers one command's output to another as input. The cool thing about named pipes is that they allow programs in different terminals and among different users to communicate. As Linux treats named pipes as ordinary files, we can even set their permissions!
mkfifo name_of_pipe # create a named pipe
command > name_of_pipe # direct output to named pipe as if it's a file
command < name_of_pipe # accept input from named pipe; can be done as different userNow you have the basics of redirection with files and pipes! Have a nice day :)

1 comment:
Hey Sam, it's Scott(Al's friend)! I came across your blog from facebook and so far I love it! Lots of interesting stuff on here :D And a linux user too! I couldn't have asked for more ;)
I thought this was a really cool command. I've never thought about how to make one, but I suppose this command could be used to make a chat program from scratch. What do you think? :)
Post a Comment