if [[ $COMP_CWORD -le $cmd_index ]]; then
# The user has not specified a command yet
local all_commands="$(tmux -q list-commands | cut -f 1 -d ' ')"
COMPREPLY=( ${COMPREPLY[@]:-} $(compgen -W "${all_commands}" -- "${cur}") )
I am trying to understand above code snippet for tmux bash autocompletion
compgen's W argument takes a word-list. But why does it taken an extra option --
with the current word, ${cur}
as argument?
What does :-
inside flower brackets mean?${COMPREPLY[@]:-}
When i do, tmux<tab>
the completion list displayed is same as $(tmux -q list-commands | cut -f 1 -d ' ')
.
So, why do we need ${COMPREPLY[@]:-}
in the array beginning?
Best Answer
compgen -W "${all_commands}" -- "${cur}"
runscompgen
, passing it:-W
with one argument, the value of the variableall_commands
;cur
.The
--
argument marks the end of options. Even if the value ofcur
begins with a dash, it won't be interpreted as an option. This is an extremely common convention for command line option parsing.${COMPREPLY[@]:-}
is a weird one. It uses the parameter expansion construct${VARIABLE:-TEXT}
, which expands to the value ofVARIABLE
if set and non-empty and toTEXT
otherwise, in a mostly pointless way. It takes the elements of the arrayCOMPREPLY
, except that if the array is empty or undefined, it results in an empty string. Then the result is split into words and each word is interpreted as a glob pattern. This is exactly equivalent to${COMPREPLY[@]}
except whenCOMPREPLY
is not defined andset -u
is in effect: underset -u
,${COMPREPLY[@]}
would trigger an error ifCOMPREPLY
is not defined. Note in particular that this instruction does not append to theCOMPREPLY
array, it mangles it. To append to the array, the right code would beassuming that the output of
compgen
contains a whitespace-delimited list of glob patterns.