Skip to content

February 13, 2009

1

Handy unix commands for debugging

by Joe Kuan

unixI 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.

I work for iTrinegy and here are my other technical blogs

1 Comment Post a comment
  1. scaryreasoner
    Feb 14 2009

    cscope is a good one as well, though one often wishes it had some kind of stack-based memory, as it’s kind of hard to “go back to where I was before” with it.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: