Benjy Kessler
Benjy Kessler

Reputation: 7616

Completing second argument from known list

I am writing bash script. It receives two arguments. The first is just a string that the user can specify however she wants. The second argument however has to be a member of a known set, e.g. apple, banana, pinenut or pineapple. I know how to check if the parameter is legal but I find it annoying to have to type in the full word. I could shorten the parameters to a, b, pn or pa but that is hard to remember and a little ugly. Is there a way to provide auto complete so that the user can press "a+tab" and it will automatically complete to apple?

Upvotes: 1

Views: 358

Answers (1)

Benjy Kessler
Benjy Kessler

Reputation: 7616

function autocomp_fruit_script {
  local cur opts
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  fruit="apple banana pinenut pineapple"
  if [ $COMP_CWORD -eq 2 ]; then
    COMPREPLY=( $(compgen -W "${fruit}" -- ${cur}) )
    return 0
  fi
}
complete -o nospace -F autocomp_fruit_script fruit_script

Where fruit_script is my script.

Upvotes: 1

Related Questions