Bash autocompletion for an environment variable holding a directory name

autocompletebash

I'm using, among other things, bash 4.2.37 on Linux Mint 14.

When I autocomplete the name of an environment variable by typing Tab, it expands to the name of the variable followed by a space.

If the value of the variable happens to be a directory name, I want it to expand to the name of the variable followed by /.

For example, if I type:

$ ls $HOM<tab>

it expands to:

$ ls $HOME _

where _ marks the location of the cursor. The problem is that I then usually want to continue typing the name of some file or directory under my home directory, which means I have to type backspace and then /.

So I want the above to expand to:

$ ls $HOME/_

The same thing happens when I've typed the entire variable name; after ls $HOME, tab adds a space, and I want it to add a /.

(And of course I don't want it to add a / if the variable's value is not a directory name.)

Is there some way I can tell bash to behave the way I want, either via bash commands or by updating my $HOME/.inputrc?

Note: I'm specifically looking for a way to make tab behave the way I want. Ways to achieve the same behavior with different keystrokes would be interesting, but would not answer my question.

(I've disabled /etc/profile.d/bash_completion.sh on my system because it interacts poorly with set -o nounset. A quick experiment indicates that this is probably not relevant to my question.)

Incidentally, tcsh does this: given an environment variable $FOOBAR, typing $FOOBA<tab> expands to $FOOBAR/ if it refers to a directory, $FOOBAR (with a space) if it doesn't. No, that's not enough to persuade me to go back to tcsh. zsh does this as well.

Best Answer

shopt -s direxpand

will help, there will be no space so you can continue typing but it will replace the enviroment variable with its content.

See also https://stackoverflow.com/questions/6418493/bash-variable-expansion-on-tab-complete