Sample Header Ad - 728x90

Can a bash script include its own auto-completions?

12 votes
3 answers
9371 views
There are many resources available (1 , 2 , 3 ) that explain how to make use of bash's ability to auto-complete commands and arguments, but all of these resources require the addition of code to a user's ~/.bash_profile or /etc/bash_completion.d/* but is there a way to make a script and its available completions self-contained? As a crude and _incomplete_ example: **~/bin/script-with-integrated-autocomplete.sh**:
#!/usr/bin/env bash

function _completions {
  complete ...
}

if [ "$1" == "completions" ]; then
  _completions
  exit 0
fi

# (Whatever the script really does goes here.)
# ...
# ...
The deal-breaker (in the context of this question) is that the above example still requires you to add something like ~/bin/script-with-integrated-autocomplete.sh completions to your .profile to engage the completions. **Is there a way for a single bash script (file) to declare its own completions and have bash recognize them _at the time of invocation_ (ideally with no additional system or environment setup)?**
Asked by beporter (223 rep)
Jan 29, 2020, 04:04 PM
Last activity: Apr 4, 2023, 05:20 PM