Bash auto complete for environment variables [closed]

The bash autocomplete feature does not seem to work with environment variables in 11.04. The current behavior is indicated below

export SCRIPT=/home/user/script
cd $SCRIPT/<tab>

results in a backslash (\) being added before $SCRIPT i.e. the prompt becomes

cd \$SCRIPT/

Same thing happens if cd is substituted with ls or any other command

Also, if there is an executable file in the path contained in $SCRIPT and I want to run that

$SCRIPT/<tab>

Bash does not show the options inside the folder (regardless of whether there is a single file or multiple files/directories inside the path contained in the environment variables).

In other words, autocomplete does not work with environment variables.


This bug was introduced in bash 4.2. There's a lengthy thread about it here:

http://lists.gnu.org/archive/html/bug-bash/2011-02/msg00274.html

In short, Chet Ramey, the developer of bash, isn't sure how to go about fixing it yet.


To get the old behaivior back, use the command

shopt -s direxpand

or include it in your .bashrc

If you use the same .bashrc with different versions of bash, use

if ((BASH_VERSINFO[0] >= 4)) && ((BASH_VERSINFO[1] >= 2))
    then shopt -s direxpand
fi

The workaround suggested in http://lists.gnu.org/archive/html/bug-bash/2011-02/msg00274.html is:

  1. use <Tab>to auto-complete your environment variable s.t. you command line says cd $MYVAR
  2. hit <Esc>+<Ctrl>-E to expand the current command line i.e. substitute $MYVAR by its value, the path
  3. add a / and then enjoy <Tab> auto-completion as usual

This assumes you are in emacs mode (set -o emacs) and have bash_completion set up sensibly for cd (e.g. complete -o nospace -F _cd cd).

Unfortunately this doesn't work in vi mode (set -o vi) because command line expansion is not available then.