Purging the process, Part 2

Unix Insider |  Operating Systems

Last month I covered several basics, such as input redirection:


$ grep "hello" <hello.txt
say hello.

Output redirection:


$ grep "hello" >junk.txt
Now is the time
for every good person to
say hello.
(type control-D here)
$ cat junk.txt
say hello.
$

Input and output redirection, and the use of input files on the command line instead of redirected input:


$ grep "Now" <hello.txt >junk.txt
$ grep "Now" hello.txt >junk.txt

Appending additional data to a file using an output redirection:


$ echo "Now is the time" >hello.txt
$ echo "for every good person to" >>hello.txt
$ echo "say hello." >>hello.txt
$ cat hello.txt
Now is the time
for every good person to
say hello.
$

Redirecting standard output and standard error, and redirecting standard error to the /dev/null byte wastebasket:


$ find / -name *.txt -exec ls -l {} \; 2>/dev/null >textfiles
$

Basic pipes:


$ grep "hello" < hello.txt | sed -e "s/hello/bye/" > result.txt
$( grep "hello" | sed -e "s/hello/bye/" ) < hello.txt > result.txt
$

I also stated that redirecting output to an existing file would delete the file and create a new version of it. In the following example, the fourth line causes hello.txt to be overwritten with a new version of the file containing only a single line, bye.


$ echo "hello" >hello.txt
$ cat hello.txt
hello
$ echo "bye" >hello.txt
$ cat hello.txt
bye

You can set the noclobber option to prevent redirected files from automatically overwriting their predecessors. In the following example, the option causes an error message at line six when the user tries to overwrite the hello.txt file.


$ set noclobber
$ echo "hello" >hello.txt
$ cat hello.txt
hello
$ echo "bye" >hello.txt
File "hello.txt" already exists
$ cat hello.txt
hello
unset noclobber

If noclobber is set, you can force a redirection to clobber any pre-existing file by using the >| redirection operator. This operator looks like a redirection to a pipe, but it's actually just a force redirect to override the noclobber option. In the following example the forced redirection operator prevents any error messages.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question