Properly handling spaces and quotes in bash completion

后端 未结 5 2013
悲&欢浪女
悲&欢浪女 2020-12-05 06:54

What is the correct/best way of handling spaces and quotes in bash completion?

Here’s a simple example. I have a command called words (e.g., a dictionar

5条回答
  •  盖世英雄少女心
    2020-12-05 07:48

    Pipe _find_words through sed and have it enclose each line in quotation marks. And when typing a command line, make sure to put either " or ' before a word to be tab-completed, otherwise this method will not work.

    _find_words() { cat words.dat; }
    
    _words_complete()
    {
    
      COMPREPLY=()
      cur="${COMP_WORDS[COMP_CWORD]}"
    
      local IFS=$'\n'
      COMPREPLY=( $( compgen -W "$( _find_words | sed 's/^/\x27/; s/$/\x27/' )" \
                             -- "$cur" ) )
    
    }
    
    complete -F _words_complete words
    

    Command line:

    $ words "ba░
    

    tab

    $ words "bar ░
    

    tabtab

    bar one  bar two
    $ words "bar o░
    

    tab

    $ words "bar one" ░
    

提交回复
热议问题