在bash脚本中读取和制表完成目录名称

时间:2022-04-12 00:29:34

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.

到目前为止,我已经使用“read -e”为文件和目录提供了tab-completion工作。我只希望当用户按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?

当用户按Tab键而不是文件和目录列表时,如何使bash只返回目录列表?

2 个解决方案

#1


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

另一种为您提供灵活性的方法是使用compgen;详情请见我的答案。

#2


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.

这是我对这个问题的快速看法。出于某种原因,由于使用了pushd和popd,我不得不实际使用bash而不是在我的计算机上。我认为这个评论已经足够让我不再解释了。

#!/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.

但雅各布的反应可能比我的更有效率和更清洁。

#1


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

另一种为您提供灵活性的方法是使用compgen;详情请见我的答案。

#2


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.

这是我对这个问题的快速看法。出于某种原因,由于使用了pushd和popd,我不得不实际使用bash而不是在我的计算机上。我认为这个评论已经足够让我不再解释了。

#!/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.

但雅各布的反应可能比我的更有效率和更清洁。