Redirection and pipes Flashcards
Redirection (stdout)
Command > destination
If the destination file does not exist, then it is created and the output of the command is added to the file.
If the destination file does exist, its contents removed and the output of the command is added to the file.
Redirection (stdout appending)
Command >> destination [user@unix demo]$ echo "line 1" >> afile [user@unix demo]$ echo "line 2" >> afile [user@unix demo]$ cat afile line 1 line 2 [user@unix demo]$
Redirection (stderr)
Command 2> destination
Example with stderr redirection
[user@unix demo]$ mv afile ./dir/xxx 2> /dev/null
[user@unix demo]$
Redirection (stderr to stdout)
Command > destination 2>&1
E.g. ls -l file1 afile > bfile 2>&1
Allows for the error messages in stderr to be sent to stdout.
In most case you will want to manipulate the error message. For this to work you will need to pipe the stderr into a command, however pipes work with stdout and not stderr.
Piping
Unix commands can be combined together
Eg. command | command | command
The stdout of the command on the left of the ‘|’ becomes the stdin of the command on the right of the ‘|’.
Eg. ls | wc -l
Example pipes 1
[user@unix demo]$ echo “hello world” | wc –c
12
[user@unix demo]$
tee command
Writes the output of a command to stdout and simultaneously sends the output to the specified files
Example basic tee example [user@unix demo]$date | tee tee-file Sun Jan 8 15:35:54 GMT 2012 [user@unix demo]$cat tee-file Sun Jan 8 15:35:54 GMT 2012
Useful for storing intermediate results when passing its output onto a pipe.
Input redirection
< : Redirect stdin
Command < source
Is used to feed data into a command from a file.
stdin redirection is mainly used in situations where you want to automate a command, such as testing or configuration
Example with stdin redirection
[user@unix demo]$ sh /student_files/day1/stdin-example < /student_files/day1/names
Your full name is bob smith
[user@unix demo]$
The above example means: run the script “stdin-example” and the data source is from this path: /student_files/day1/names