The grep command is a powerful tool for searching for text in files. However, it can sometimes report “Binary file matches” if the file it is searching contains binary data. This is because grep by default assumes that a file is binary if the first few bytes of the file indicate that it contains binary data.
Today I found an interesting grep alert when trying to find whether my cron job is running or not.
[root@server ]$ cat /var/log/cron | grep something.php
Binary file (standard input) matches
[root@server ]$
I’ve done something like this for as long as I know, none of above alert ever comes up.
So, why grep comes up with those alert?
Here is a clue from grep manual:
If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type type. By default, type is ‘binary’, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If type is ‘without-match’, grep assumes that a binary file does not match; this is equivalent to the ‘-I’ option. If type is ‘text’, grep processes a binary file as if it were text; this is equivalent to the ‘-a’ option. Warning: ‘–binary-files=text’ might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands.
As you reckon, we need to add -a option.
[root@server ]$ cat /var/log/cron | grep -a something.php
....
Apr 27 00:00:01 server crond[9475]: (root) CMD (cd /var/www/html/ ; /usr/bin/php something.php > /dev/null 2>&1)
Apr 28 00:00:01 server crond[29336]: (root) CMD (cd /var/www/html/ ; /usr/bin/php something.php > /dev/null 2>&1)
Apr 29 00:00:01 server crond[23088]: (root) CMD (cd /var/www/html/ ; /usr/bin/php something.php > /dev/null 2>&1)
[root@server ]$
No Comments