Home > Blockchain >  Simulate Bash's COMPREPLY response without actually completing it
Simulate Bash's COMPREPLY response without actually completing it

Time:01-02

Steps to reproduce

  • Create directory on tmp, add 1 file inside.

    mkdir /tmp/testdir && touch /tmp/testdir/examplefile
    
  • Paste below script on /tmp/completion.sh

    # BEGIN AUTOCOMPLETE
    function _foo_complete() {
    local comnum cur opts
    [[ "${COMP_WORDS[@]}" == *"-"* ]] && comnum=2 || comnum=1;
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    opts="--help --restart -h -r"
    if (( COMP_CWORD > comnum )); then
     COMPREPLY=( $(for filename in "/tmp/testdir/"*; do echo ${filename##*/}; done) )
     return
    fi
    if [[ ${cur} == -* ]]; then
     COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
     return 0
    else
     COMPREPLY=( $(for filelist in /tmp/testdir/"$2"*; do echo ${filelist##*/}; done) )
    fi
    }
    complete -F _foo_complete foo.sh
    # END AUTOCOMPLETE
    
  • Source it then.

    . /tmp/completion.sh
    

Expected result

$ foo.sh --restart examplefile <tab><tab>
examplefile           
$ foo.sh --restart examplefile <tab><tab>
examplefile        
$ foo.sh --restart examplefile <tab><tab>
examplefile     
$ foo.sh --restart examplefile <tab><tab>

What happen instead

$ foo.sh --restart examplefile <tab><tab> examplefile <tab><tab> examplefile <tab><tab> examplefile <tab><tab> examplefile <tab><tab> examplefile

I want the suggestion to appear as possible completion, but without actually completing it (for display purposes). This question has been asked enter image description here

CodePudding user response:

compgen -G '/home/user/testdir/*' | awk '{ gsub(/.*\//, "") } 1' | column | less -qFS

Plus proper completion setup to your myscript command.

awk could be just sed actually, but it allows you to play around with ORS.

  • Related