How to use ls's bash-completion of specific directory for my bash command?

放肆的年华 提交于 2020-07-23 04:01:28

问题


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

auto-complete



来源:https://stackoverflow.com/questions/62979947/how-to-use-lss-bash-completion-of-specific-directory-for-my-bash-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!