TimeLinux1

Friday, October 22, 2010

Linux HowTo: Redirection Basics

Linux (like Unix) comes with the very powerful command line option of input, output and error redirection. In simple terms it means taking the input and showing the output and/or error on non default sources. Note that the standard devices are Std in = 0, Std out = 1 and Std err = 2.


-To redirect both standard output and standard error into a file the following operator is used:
- &> or &>>
-eg      # cmd > output.txt 2>&1
-eg      # cmd > /dev/null 2>&1
-note: . this discussion didn't talk about redirecting standard input (only standard output and standard error).
. so this form of redirection works only for standard output and standard error.

-input redirection works like this:
           # cmd < afile
-eg:     # sort  < afile            [ it is just like sort abc ]

-'here document' is a special type of input redirection where a redirector is << and a word is used a marker for start and end.
          # cmd << keyword
              bla bla
           keyword
-eg:    # sort <<st                [ here the chosen keyword = st ]
          > a
          > Q
          > A
          > b
          > st
          A                                 [ <-- sorted output started from here ]
          Q
          a
          b
numbers

-pipelines ( a series of pipes ) only only work between stdin and stdout.
-stderr can not be piped.
 
eg:      # cat afile | grep 'test'  |  sort  |  uniq -c                       - sorts and counts unique occurances of word 'test' in file called afile.

No comments:

Post a Comment