Handy unix commands for debugging
I spend most of my time in my job reading other peoples’ code or kernel source code than writing my own. These code can be scattered into many directories in multiple levels. I constantly have to do ‘find’ and ‘grep’ to trace variable and function names. Typing these commands manually can add up a lot of time.
Here are a list of simple alias commands that I always use. Hope you will find it useful.
alias fc=’find . -name “*”.c | xargs grep -n’
alias fh=’find . -name “*”.h | xargs grep -n’
alias fch=’find . -name “*”.[ch] | xargs grep -n’
The idea is to either only find C (fc), header (fh) or both type of files (fch). You may suggest using grep -R, however this will contaminate the results with search in binary files.
So if I need to trace where a variable (let say type) is being assigned which is likely in C source files, I can do
fc ‘type = ‘ or fc ‘type =[^=]’
In my case, it generally returns several pages of results due to the size of source code. Some of the results partially contain the word type, like the followings:
./ip_input.c:1953: type = ICMP_UNREACH;
./libalias/alias.c:943: proxy_type = 0;
./libalias/alias_pptp.c:315: *ptype = ntohs(hptr->type);
and if I need to narrow the results down to exact word – type, simply relaunch the command as:
fc ‘<type> = ‘
You can combine many useful grep options with fc such as
-i case insensitive
-A n output n lines before the match result
-B n output n lines after the match result
-C n output n lines before & after the match result
You can adapt this scheme into other programming languages for your project. Make it as a habit and you will save a lot of time.
If you know better unix commands for debugging or tracing code, please drop me a comment.