Hello.
I recently stumbled upon a really nice post, detailing how you can make a Bash alias, and at the same time ensure autocompletion works as per the original command.
The example here will be systemctl
(and related commands) on Ubuntu - but I imagine this works with other commands and distributions as well.
This is my ~/.bash_aliases
, defining shorter commands for systemctl
etc.:
alias gctl='loginctl'
alias hctl='hostnamectl'
alias jctl='journalctl'
alias lctl='localectl'
alias sctl='systemctl'
alias tctl='timedatectl'
Now, to make autocompletion work for all these commands, I create the following file: /etc/bash_completion.d/bash_completion
with these contents:
# Bash completion for "gctl", "hctl", "jctl", "lctl", "sctl" and "tctl",
if [[ -r /usr/share/bash-completion/completions/loginctl ]]; then
. /usr/share/bash-completion/completions/loginctl && complete -F _loginctl loginctl gctl
fi
if [[ -r /usr/share/bash-completion/completions/hostnamectl ]]; then
. /usr/share/bash-completion/completions/hostnamectl && complete -F _hostnamectl hostnamectl hctl
fi
if [[ -r /usr/share/bash-completion/completions/journalctl ]]; then
. /usr/share/bash-completion/completions/journalctl && complete -F _journalctl journalctl jctl
fi
if [[ -r /usr/share/bash-completion/completions/localectl ]]; then
. /usr/share/bash-completion/completions/localectl && complete -F _localectl localectl lctl
fi
if [[ -r /usr/share/bash-completion/completions/systemctl ]]; then
. /usr/share/bash-completion/completions/systemctl && complete -F _systemctl systemctl sctl
fi
if [[ -r /usr/share/bash-completion/completions/timedatectl ]]; then
. /usr/share/bash-completion/completions/timedatectl && complete -F _timedatectl timedatectl tctl
fi
Next time you login (or run source /etc/bash_completion
), autocompletion now works for the aliases, exactly as for the original commands.
The original post is here on Ask Ubuntu for reference
Have a nice weekend.