Why You Should Always Grep Carefully If Your Search String Has ">" In It.


It's Better "Quoted" Than "Naught"ed!
Behold the mighty little ">" symbol in a Unix/Linux grep command. If not quoted, it will empty the file being searched.
EASY EMPTY
If you've been on the Unix/Linux platforms for a while, I am sure that you'll remember this good old technique to empty files.>test.logThis command nulls out the test.log file and is usually used to empty fat old error files and log files.
THE DANGER OF UNQUOTED ">" WITHIN A GREP COMMAND
While the command above is perfectly fine, accidents do happen especially if and when we are dumb, careless or in a big hurry! That's why we better watch out for the greater than symbol [">"] used carelessly in a grep command. If it is not quoted, it empties the file. Makes it 0 bytes. Zero. Zilch. Nada. Naught. Nothing! What a nightmare! There's no way out except with a backup. It doesn't matter it is a 1KB file or 1GB. There is nothing left in the file so you can try the "string" command or similar. How dangerous!
EXAMPLE
Let us prove this with an example. Look at the image above. We have a test file called hworld1.log and we are going to search for a string "echo hello >" within the file. First look at the file itself.$cat hworld1.log
#!/bin/sh
#Beware the greater than symbol in a grep command. Always quote it!
touch hello.log
echo hello>hello.log
echo world>>hello.log
ls -l hello.log
exit
CORRECT USAGE OF THE GREP COMMAND
To search for the string "echo hello >" within the hworld1.log file, type
Tested on Puppy Lucid 510. Puppy Linux allows both single and double quotes within the grep command. Check with your Unix/Linux platform for details on how things work with regard to single or double quotes.
$grep "echo hello >" hworld1.logand everything is fine. Check the image above.
DANGER! INCORRECT USAGE
Suppose you are in a hurry to go out and you accidentally forget to quote your > symbol in your grep command. Now it is not part of the search string you intend it to be anymore. The grep command looks for part of the search string [echo] in the wrong place [non-existent hello file] and the input file [hworld1.log] is overwritten with null instead! Never try
$grep echo hello > hworld1.logor else the hworld1.log file is nulled out! Check the image above.