views:

374

answers:

2

I want to prompt the user for a directory name, and have them able to tab-complete to a valid directory.

So far, I've got tab-completion working for both files and directories using "read -e". I only want directories to be autocompleted when the user presses tab.

Here's what I have:

echo "Enter a directory"
read -e -p "> " DEST

How can I make bash only return a list of directories when the user presses tab, rather than a list of files and directories?

+2  A: 

An alternate approach that gives you a lot of flexibility is to use compgen; see my answer here for details.

JacobM
Sounds good. Any idea how to integrate that with tabbing though?
nfm
A: 

Here's my quick take at the problem. For some reason I had to actually use bash and not sh on my computer, due to the use of pushd and popd. I think it's well commented enough for me to not explain it any further.

#!/bin/sh
tempdir=`mktemp -d`

# save the current directory
pushd .  

# make a new folder, then make a bunch of new directories 
# mirroring those in our current directory
for i in $(find . -type d); do mkdir "$tempdir/$i" ; done

# change to the temporary directory
cd "$tempdir"

echo "Enter a directory"
read -e -p ">" DEST

echo "You told me $DEST"

# return to our original directory
popd

# clear out that temporary directory we made
rm -rf "$tempdir"


But Jacob's response is probably more efficient and cleaner than mine.

Mark Rushakoff
read -e -p autocompletes both directories _and_ files. You can also use `cd -` rather than pushing and popping the original directory.
nfm