Skip to content

Instantly share code, notes, and snippets.

@Hiweus
Created December 9, 2024 02:47
Show Gist options
  • Save Hiweus/552aeca04c2c3f2fe7313c6ab7159aa1 to your computer and use it in GitHub Desktop.
Save Hiweus/552aeca04c2c3f2fe7313c6ab7159aa1 to your computer and use it in GitHub Desktop.
bash autocompletion

Autocomplete

bash shell generally handle autocomplete using a specific function, example:

My function

function aa() {
  echo "$@";
 }

Autocomplete options

function _aa() {
  # Get the current word (could be in the middle of a string)
  cur=$(_get_cword)

  # Define the list of words/phrases (the options)
  WORDS=("cole" "mano" "estou aqui")

  # Prepare COMPREPLY with words/phrases that contain $cur anywhere
  COMPREPLY=()
  
  # Loop over the array, this is necessary to keep words with white space together in options
  for word in "${WORDS[@]}"; do
    # Check if $cur is anywhere in the word/phrase
    if [[ "$word" == *"$cur"* ]]; then
      # Add the word to array of options
      COMPREPLY+=("$word")
    fi
  done
}

Configure the completion

# _aa is the function who complete
# aa is the feature function
complete -F _aa aa

Every time you hit tab the completion function _aa will be called and the values available inside the variable COMPREPLY will be the completion suggestion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment