Friday, March 17, 2006

Bash completion for Sql*Plus

If most people are like me, you don't like to type something twice. Here's something I wrote a while back to add completion to sqlplus in bash. I had copied it to a new machine to and thought I'd post it in case someone might find it usefull so here it is.


This file will check the ~/.bash_history for previous sqlplus commands as well as complete @.../foo.sql

To try this grab this and drop it into the ~/.bashrc or ~/.bash_profile. If Bash Completion is loaded, it can be dropped into /etc/bash_completion.d/ .


------FILE-------
_sqlplus()
{
local cur
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}

if [ $COMP_CWORD -eq 1 ] && [[ "$cur" == -* ]]; then
# return a list of switched
COMPREPLY=( $( compgen -W '-H -V -C -L -M -R -S' -- $cur ) )
elif [[ "$cur" == "/" ]]; then
# only /nolog is possible
COMPREPLY=( $( compgen -W '/nolog' -- $cur ) )
elif [[ "$prev" == "as" ]]; then
# as sysdba sysoper
COMPREPLY=( $( compgen -W 'sysdba sysoper' -- $cur ) )
elif [[ "$prev" == "-R" ]]; then
# added for completness
COMPREPLY=( $( compgen -W '1 2 3' -- $cur ) )
elif [[ "$cur" =~ "@" ]]; then
# if @
base=${cur:1}
COMPREPLY=( ${COMPREPLY[@]:-} $( compgen -f -P "@" -X "$xspec" -- "$base" ) $( compgen -d -P "@" -- "$base" ) )
elif [[ "$prev" =~ "@" ]]; then
# if @
COMPREPLY=( ${COMPREPLY[@]:-} $( compgen -f -P "@" -X "$xspec" -- "$cur" ) $( compgen -d -P "@" -- "$cur" ) )
elif [[ "$*" =~ "/" ]] ;then
# already has a / assume it's the pass
COMPREPLY=
else
#default
_history
fi
}
complete -F _sqlplus $nospace $filenames sqlplus


_history()
{
local cur
cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $( compgen -W '$( command grep "^sqlplus" ~/.bash_history ) ' -- $cur ) )
}
------FILE-------

If you notice the history funcion is pretty simple so modifying it to check other files would be very easy

No comments:

Disqus for Kris' Blog