unix/linux redirection: empty files without typing /dev/null

Subtitled, Figurative and Literal Redirection, a post in which I alter my approach to redirection with explict shell redirection indicators.

When I  started working with Unix, I generally used ”cat /dev/null’ to empty a file quickly and cleanly, e.g.,:

foozbear% cat /dev/null > big_useless_log

foozbear% cat /dev/null > /var/mail/mymail

This, of course, made big_useless_log or mymail empty (zero length), and did so without getting rid of it, in case a data write was imminent. 

This week I was using a lot of temp files — actually using the same temp file over and over to hold data I’d scraped from Cisco switch output so I could point some ‘awk’ at it for parsing purposes (or, vice versa, really). For some reason, I decided to see what would happen if instead of removing and recreating the file (or more laboriously, typing cat /dev/null > temp), I used a redirection symbol, i.e.,
foozbear% > temp
Well, this worked as well as my previous steps, so I started alternating (using the command line up arrow) between my temp file resetting/editing
foozbear% > temp && vi temp
and my grep/awk line:
foozbear% egrep 'Gig|Fas' temp | awk '{print "interface "$2" "$3"n description "$1}'

This worked fantastically (note that I was using bash under Ubuntu here), and a good time was had by all (the Cisco switches were particularly pleased, having their cdp output turned into port descriptions so handily — but perhaps I’ll expand on that later).

The redirection symbol also can be used if you are too lazy to create an empty file using ‘touch’. Instead of
foozbear% touch newfile
just type
foozbear% > newfile
and you’re all set.

Leave a Reply

You must be logged in to post a comment.