Command Completion Output – How to Redirect

autocompletebashio-redirectionpipe

On the command line, I can redirect or pipe output of a command to a file or another command using the > or | operator after the command. I have come across a less standard situation that I would like to redirect the output to a file, but I don't seem to have the oppurtunity to redirect it:

When at a new terminal,

[chiliNUT ~]$

if I press Tab without typing anything first, I get asked

display all 1725 possibilities? (y or n)

and if I then type y, I get a nice long list of different commands. How can I redirect or pipe this output to a file? I don't seem to get the chance to type > myfile.txt anywhere.

Using CentOS release 6.4 (Final).

Best Answer

You could make use of the builtin compgen:

compgen: compgen [-abcdefgjksuv] [-o option]  [-A action] [-G globpat]
[-W wordlist]  [-F function] [-C command] [-X filterpat] [-P prefix]
[-S suffix] [word]

    Display possible completions depending on the options.

    Intended to be used from within a shell function generating possible
    completions.  If the optional WORD argument is supplied, matches against
    WORD are generated.

    Exit Status:
    Returns success unless an invalid option is supplied or an error occurs.

TAB at the prompt would list commands, shell builtins, keywords, aliases and functions. So you could say:

compgen -cbka -A function | grep '^y' > myfile.txt

to get all the options that you see upon typing yTAB at the shell prompt into the file myfile.txt.

Eliminate the grep pipeline in order to get all the possible commands, functions, ... into the file:

compgen -cbka -A function > myfile.txt
Related Question