notebox

Tab Completion for Bash Script Sub-Commands

Taking advantage of the Programmable Tab Completion in Bash, Bash scripts that have subcommands can provide TAB completion in order to discover these subcommands in the following manner:

  1. Gather a list of subcommands dynamically, say in a list COMMANDS

  2. Use the following code to give completion output

      if [[ -n $COMP_LINE  ]]; then
        line=${COMP_LINE#* }
        for c in "${COMMANDS[@]}"; do
          [[ ${c:0:${#line}} == "${line,,}" ]] && echo "$c"
        done
        exit
      fi
    

    Explaination:

    • Check to see if we are in Tab completion mode. Presence of COMP_LINE is an indication or this.
    • Get the current word we are typing.
    • Match the incomplete work with names of commands in COMMANDS
    • echo any sub-commands that match
  3. Add complete -C prog prog to ~/.bashrc, where prog is the program that the above completion code would be a part of.

Related:

Reference:

Tags:

#literature-note #scripting #tips