$ ssh fo<tab>
foo  fool  football

How would I write a for loop to iterate over those values?

#!/usr/bin/env bash
for SERVER in $(ssh fo<MAGIC HERE>) ; do echo $SERVER ; done

The list could change regularly, so hardcoding the values is not an option. In the specific case of SSH, I understand that I could grep the SSH config file for the matching hosts. But some other completion situations arise, such as:

$ git che<tab>
checkout      cherry        cherry-pick

The answer should be useful for these other ad-hoc completions as well.

  • 1
    @Theophrastus Thank you, I'll see where I can run with it. This quote is terrific: It has been extensively documented that programmers are willing to put in long hours of effort in order to save ten minutes of "unnecessary" labor. This is known as optimization.
    – dotancohen
    Dec 18, 2020 at 0:51
  • What's the use case for iterating over the git sub-commands?
    – Kusalananda
    Dec 18, 2020 at 8:07
  • Maybe this post of 2015 is useful: brbsix.github.io/2015/11/29/…
    – thanasisp
    Dec 18, 2020 at 9:12
  • I think that a couple of additions are required for your description, for example ls - would return only ls -- and needs processing again to get all compination after that.
    – thanasisp
    Dec 18, 2020 at 9:13

1 Answer 1


compgen will work only with one word, like the following :

compgen -c git 

Here is a custom solution for your case :

You will have first to source bash-completion script, then set the COMP_* vars so they meet this use case and then trigger programmatically the completion with the native bash_completion function xfunc and the results will then be gathered in COMPREPLY array (example taken from here):

# load bash-completion helper functions
source /usr/share/bash-completion/bash_completion

# array of words in command line
COMP_WORDS=(git c)

# index of the word containing cursor position

# command line
COMP_LINE='git c'

# index of cursor position

# execute completion function
_xfunc git _git

# print completions to stdout
printf '%s\n' "${COMPREPLY[@]}"

P.S : To know the exact functions called during a command completion : use complete -p <command>

Output :


For a full overview of this, you can visit the owner post here

  • This is terrific! I feel like Harry Potter discovering a new spell!
    – dotancohen
    Dec 18, 2020 at 1:05
  • hihi please don't forget to mark it as resolved if it's the case :)
    – Reda Salih
    Dec 18, 2020 at 1:11
  • I'm going to give the question a day or two to develop additional answers before marking, which is SOP here. Thank you!
    – dotancohen
    Dec 18, 2020 at 1:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .