Pro-tip: Creating aliases in Bash with autocompletion enabled


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

if [[ -r /usr/share/bash-completion/completions/hostnamectl ]]; then
    . /usr/share/bash-completion/completions/hostnamectl && complete -F _hostnamectl hostnamectl hctl

if [[ -r /usr/share/bash-completion/completions/journalctl ]]; then
    . /usr/share/bash-completion/completions/journalctl && complete -F _journalctl journalctl jctl

if [[ -r /usr/share/bash-completion/completions/localectl ]]; then
    . /usr/share/bash-completion/completions/localectl && complete -F _localectl localectl lctl

if [[ -r /usr/share/bash-completion/completions/systemctl ]]; then
    . /usr/share/bash-completion/completions/systemctl && complete -F _systemctl systemctl sctl

if [[ -r /usr/share/bash-completion/completions/timedatectl ]]; then
    . /usr/share/bash-completion/completions/timedatectl && complete -F _timedatectl timedatectl tctl

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. :smiley: :sunglasses:


Neat! :penguin:

You should be able to make a ~/.bash_completion file, too, and have it sourced using the same little code block in your ~/.bashrc that it uses to source your ~/.bash_aliases. :smile_cat:

1 Like

Yeah, I think it’s up to your own taste if you want the autocompletion file sourced from /etc/bash_completion.d automatically, or from ~/.bashrc by yourself. I guess this will depend on whether this should be a systemwide or user-only setting.

Well, I think generally if you make the aliases per-user, the completions for them should be too?

That makes sense. But since it’s my own homelab, I’m the only “real” user, so it doesn’t make any difference in my case. :wink: