8

I tried

alias sct='systemctl'
complete -F _systemctl sct

But the function _systemctl is not found until I run the original command systemctl in the session. This function loads dynamically or somehow and contains many other same functions inside.

OS - Ubuntu 20.04

tehkonst
  • 363

3 Answers3

11

Create a file named /etc/bash_completion.d/systemctl:

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

You can restart bash-completion by sourcing . /etc/bash_completion

3

I found a file with autocomplete functions for systemctl in my system and added a line to load it:

source /usr/share/bash-completion/completions/systemctl
alias sct='systemctl'
complete -F _systemctl sct
tehkonst
  • 363
2

Just

alias sct='systemctl'
_completion_loader systemctl
complete -F _systemctl sct

But I recommend use bash function instead of bash alias so you can define some shortcuts for sub commands, here is an example:

sct ()
{
    case $1 in
        e)
            shift;
            sudo systemctl enable --now "$@"
        ;;
        d)
            shift;
            sudo systemctl disable --now "$@"
        ;;
        s)
            shift;
            systemctl status "$@"
        ;;
        S)
            shift;
            sudo systemctl stop "$@"
        ;;
        r)
            shift;
            sudo systemctl restart "$@"
        ;;
        *)
            systemctl "$@"
        ;;
    esac
}

In addition, in order to make bash completion work for these shortcuts, you need to add them to array VERBS in corresponding keys in /usr/share/bash-completion/completions/systemctl. Here is an example for sct e :

    local -A VERBS=(
        ...
-       [DISABLED_UNITS]='enable'
+       [DISABLED_UNITS]='enable e'
        ...
    )

But these modifications in /usr/share/bash-completion/completions/systemctl may lost over an update. I haven't found a perfect way to override it yet, maybe later.

alzee
  • 121