Course contentsShow
← Linux
Lesson 213 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Shell-Level Autocomplete Development

Provide custom command-line completion for your tools.

In this lesson, you will learn how to supercharge your custom scripts by teaching the Bash shell how to predict and auto-complete your command arguments using the complete built-in.

Why Autocomplete Matters

As you build more complex tools, remembering every flag or sub-command becomes a burden. By providing custom completion, you transform your script from a simple utility into a professional-grade command-line interface. Instead of the user guessing what arguments your script accepts, the shell provides them with a [TAB] key press.

The Mechanism: complete

Bash uses a built-in command called complete to link a function or a list of words to a specific command name. When you press [TAB], Bash executes the logic you’ve defined to generate a list of possible completions.

Consider a tool you’ve written called monitor.sh that accepts two modes: start and stop. You can define the completion logic like this:

# Define the list of valid options
_monitor_completions() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    COMPREPLY=( $(compgen -W "start stop status" -- ${cur}) )
}

# Link the function to your script
complete -F _monitor_completions monitor.sh

Breaking Down the Logic

  1. _monitor_completions: This is a helper function. The COMPREPLY variable is an array where you store the suggestions you want to show the user.
  2. compgen -W: This command generates a list of words (-W) and filters them based on what the user has already typed (${cur}).
  3. complete -F: The -F flag tells Bash to run your function whenever someone tries to auto-complete the monitor.sh command.

Once this code is sourced in your shell (typically via your .bashrc or a dedicated script in /etc/bash_completion.d/), typing monitor.sh [TAB] will instantly suggest start, stop, or status.

This approach keeps your scripts interactive and error-resistant. Instead of handling "invalid argument" errors manually, you prevent the user from typing incorrect commands in the first place. You are effectively shifting your UI design into the shell’s core interaction layer, making your tools feel like native parts of the operating system.

Key Takeaway: Use the complete command coupled with a compgen function to provide dynamic, context-aware suggestions that make your scripts faster and safer to use.