问题
I created a command memo
as follows:
memo() {
vi $HOME/memo/$1
}
I want to apply bash-completion to my memo
to open files that is already in $HOME/memo
directory:
$ memo [TAB] # to show files in $HOME/memo
$HOME/memo
contains directory, so listing the file under memo
is not sufficient.
In other words, I want to apply what is used in ls
command in $HOME/memo
to memo
:
$ ls [TAB]
foo.md bar/
I tried the below but it doesn't work for nested directories:
_memo() {
local cur
local files
_get_comp_words_by_ref -n : cur
files=$(ls $MEMODIR)
COMPREPLY=( $(compgen -W "${files}" -- "${cur}") )
}
complete -F _memo memo
MEMODIR=$HOME/memo
回答1:
Here's a simple example:
_memo()
{
local MEMO_DIR=$HOME/memo
local cmd=$1 cur=$2 pre=$3
local arr i file
arr=( $( cd "$MEMO_DIR" && compgen -f -- "$cur" ) )
COMPREPLY=()
for ((i = 0; i < ${#arr[@]}; ++i)); do
file=${arr[i]}
if [[ -d $MEMO_DIR/$file ]]; then
file=$file/
fi
COMPREPLY[i]=$file
done
}
complete -F _memo -o nospace memo
来源:https://stackoverflow.com/questions/62979947/how-to-use-lss-bash-completion-of-specific-directory-for-my-bash-command