Sudo Alias

How to enable aliases with sudo


Posted: February 1, 2023

Ever came across this error?

$ sudo my_alias
sudo: my_alias: command not found

The solution is to enable aliases after sudo, you can do this by creating the following alias:

# ~/.bash_aliases
...
alias sudo='sudo '

Bash by default only checks the first word of a command for any aliases, unless this command is an alias ending with a space or tab. In which case the second word in the command is also checked for aliases.

This can be especially useful when executing potentially destructive commands, such as rm with root privileges. As it will allow you to use common safety aliases such as rm -i:

# ~/.bash_aliases
...
alias sudo='sudo '
alias rm='rm -i' # prompt before every removal

Which will prevent against accidental deletions when using sudo rm:

$ sudo rm some-file
rm: remove regular empty file 'some-file'?