bash command completion for jstack/jps

I’ve only recently become aware of jps and jstack, Sun’s tools for listing Java processes and for producing a thread dump from them. They beat the old ps | fgrep java and kill -3 (and then try to find the log file your thread dump went into…).

You still have to use jps, copy the appropriate pid and then paste it into your jstack command line, which is inconvenient. I decided to implement bash command completion for the pid argument.

Of course that isn’t useful by itself — seeing a list of available JVM pids tells you nothing about which one you want, so I arranged for each pid to be accompanied by the full package name for the application’s main class or the full path name to the application’s JAR file, as provided by jsp -l.

The trick is to give compgen the list of options in the form <pid>#<description>, as it splits the list of options on whitespace, but then to modify the array of options so that each is <pid> #<description> so that the description is interpreted as a comment by bash in the final command line:

    local cur prev opts
    opts=`jps -l | fgrep -v | sed -e's/ /#/' | tr '\n' ' '`
    replies=( $(compgen -W "${opts}" -- ${cur}) )
    for (( i = 0 ; i < ${#replies[@]} ; i++ ))
    COMPREPLY[$i]=`echo ${replies[$i]} | sed -e's/#/ #/'`
    return 0
complete -F _jstack jstack

The code above can be put in your .bashrc file.

Post a Comment

Your email is never shared. Required fields are marked *