Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

shell - Bash completions with equals sign and enumerable flag values

I'm trying to construct a bash completion routine that will suggest command lines flags and suitable flag values. For example in the below fstcompose command I would like the competition routine to first suggest the compose_filter= flag, and then suggest possible values from [alt_sequence, auto, match, sequence].

fstcompose --compose_filter=

For any flags that do not have a set of associated of values I want the competition to fall back to the default mode of suggesting paths or files.

The one issue I'm facing is the = equal sign treated as an individual token and is set as the prev COMP_WORD. Is there a technique for detecting the whole flag before and including the previous = character ? Or is there a better way of implementing this type completion of flag with enumerable values? Below is a sample of the completion routine I'm working with.

_fstcompose()
{
  local cur prev opts filters pprev
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD-1]}"
  opts="--compose_filter= --connect"
  filters="alt_sequence auto match sequence"

  if [[ ${cur} == -* ]] ; then
  COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
  return 0
  fi

  if [[ ${prev} == "--compose_filter=" ]] ; then
  COMPREPLY=($(compgen -W "${filters}" -- ${cur}))
  return 0
  fi
  _filedir
}
complete -o nospace -F _fstcompose fstcompose
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your first return 0 prevents the second if from being evaluated. Try using a case statement ordered from most-specific to least-specific or at least order your if statements that way.

Since "=" is included in $COMP_WORDBREAKS, ${prev} is "--compose_filter" without the "=".

If you remove "=" from $COMP_WORDBREAKS then --compose_filter is still ${cur} rather than ${prev}. Doing so without preserving and restoring its value will break other completions.

I'm not sure what other problems there may be.

You can pepper your function with echo statements that are redirected to another terminal to aid in debugging. For example:

echo "cur: $cur, prev: $prev" > /dev/pts/2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...