Skip to content

Instantly share code, notes, and snippets.

@bjpcjp
Created January 19, 2025 20:39
Show Gist options
  • Save bjpcjp/7b811b3191ab09fd4282059d91ee2349 to your computer and use it in GitHub Desktop.
Save bjpcjp/7b811b3191ab09fd4282059d91ee2349 to your computer and use it in GitHub Desktop.

The compgen command in Linux is a shell built-in used primarily for generating possible completions for commands, functions, files, or other shell elements. It is part of the Bash shell and is often utilized in scripts for tab-completion or command suggestion mechanisms.

Syntax:

compgen [option] [word]

Key Features:

  • The compgen command does not execute commands; instead, it outputs possible completions for the given input.
  • If no options or word is provided, it lists all available completions (commands, functions, aliases, etc.).

Common Options:

Here are the most commonly used options with compgen:

Option Description
-A alias Lists all aliases.
-A arrayvar Lists all array variables.
-A binding Lists all key bindings.
-A builtin Lists all shell built-in commands.
-A command Lists all executable commands in the PATH.
-A directory Lists directories in the current working directory or specified path.
-A file Lists files in the current working directory or specified path.
-A function Lists all shell functions.
-A group Lists all groups.
-A helptopic Lists all help topics.
-A hostname Lists all hostnames.
-A job Lists all active jobs.
-A keyword Lists all shell keywords (reserved words).
-A running Lists processes currently running.
-A service Lists services known to the system.
-A setopt Lists valid shell options that can be set with set.
-A shopt Lists valid shell options that can be set with shopt.
-A signal Lists all valid POSIX signals.
-A user Lists all users on the system.

Examples:

  1. List all commands in the PATH:

    compgen -A command
  2. List all aliases:

    compgen -A alias
  3. List all files and directories starting with "my":

    compgen -A file my
  4. List all shell built-ins:

    compgen -A builtin
  5. List all functions:

    compgen -A function
  6. Autocomplete suggestion for a partially typed command (e.g., "ls"):

    compgen -c ls

    The -c flag matches commands that begin with the specified string.

Notes:

  • compgen is a low-level utility and is often used in combination with other scripts or tools like complete for creating custom tab-completion rules.
  • To see the full list of options supported by your specific shell version, refer to the Bash manual or use help compgen.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment