I'm writing a CLI utility called envset, which has this usage: envset [ENVSET-OPTIONS] [SETNAME] [--] [CMD] [ARGS]....
It basically runs a command with a set of environment variables defined in a config file (there's already an npm package with the same name, but I'm implementing my utility in Perl with a different feature set).

I want to provide tab completion for envset. The completion is handled by a shell function _envset. It would be nice in the case like below (^ denotes the location of cursor when Tab is pressed):

% envset mycolors -- ls -^

_envset can return the completion answers for ls instead (so, return a list of possible ls command-line options). Is there an easy way I can ask bash to return them for me?

Otherwise, I'd have to do something like the following in _envset (which is not perfect but should be good enough for most cases):

  1. parse the output of complete to find an entry that describes how a command (in the above example, ls) is completed. If there is none, find the entry with -D (default handler).

  2. if the command is completed by function (-F), call that function (after setting COMP_WORDS and COMP_CWORD appropriately). Return the COMPREPLY from the function.

  3. if the command is completed by external command (-C), run the command (after setting COMP_LINE and COMP_POINT appropriately). Capture the output lines and set COMPREPLY.

  4. and so on for each of the other type of handler (-W, -G, etc). I think handling -F, -C, -W, and -A should cover a majority of the cases.

  5. for the default handler, there's a special case of it returning 124 which means we must restart from step 1 to see if the handler has defined complete for our wanted command.

  • Look at the completion for e.g. sudo. – Michael Homer Aug 5 '17 at 6:44
  • That's what I did before posting this question. I thought that _sudo didn't do the above, but after a second look it turns out it does. Thanks! – Gerry Lufwansa Aug 5 '17 at 7:05

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.