Bash completion of parameters when using sudo

autocompletebashcentossudo

I am using CetnOS 6 and want to have autocompletion for parameters while using sudo.

I found this question https://superuser.com/questions/804128/bash-hints-does-not-work-after-sudo-or-man and now the following works:

  • yu[tab] completes to yum and with another tab press it suggests the different yum commands
  • yum upg[tab] autocompletes to yum upgrade as desired
  • sudo yu[tab] autocompletes to sudo yum as expected
  • sudo yum upg[tab] does not autocomplete to anything, also no suggestions.

How can I achieve parameter completion even when using sudo?

(I used yum just as an example because it is available on all CentOS; the result is the same for other commands.)


Some informations about my system:

$ uname -a
Linux server 2.6.32-642.6.1.el6.x86_64 #1 SMP Wed Oct 5 00:36:12 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

$ bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

$ yum list installed | grep completion
bash-completion.noarch  1:1.3-7.el6        @epel

$ cat .bashrc
# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# User specific aliases and functions
complete -cf sudo

Best Answer

Not the perfect workaround, but you can add complete -cf sudo to your .bashrc which will autocomplete sudo commands thereon.

However, in doing so, it will not act exactly like normal tab completion. for example, if you were to use this, and then sudo cd [tab] you will get a lot of possibilities that won't be useful - i.e a file names will show... who wants to cd to a file?

For the most part though, it will complete commands like sudo yum upd[tab]