I am guessing you already know how to create alias in Linux. An alias helps you to run lengthy custom commands easily. You can make alias permanent by adding it to your bashrc or the configuration file of whichever shell you are running in Linux.
The problem arises when you try to run the alias with sudo. You’ll see an error like this:
sudo: my_alias: command not found
Here's an example. I created an alias
apt update command. The apt update command needs to run with sudo. But if I try to run
sudo up, it gives an error:
You’ll think that since you are running as root user, the alias should be defined in the bashrc of the root user, i.e. /.bashrc. Go ahead and try it but I bet it won’t work.
Let me show you a neat little trick to run an alias command with sudo.
Running alias command with sudo access
The trick is to create an alias for sudo itself like this:
The space (or tab, if you prefer that) after sudo is important in the above code. Now, if you run your alias command with sudo, it should work just fine.
But why? Why does it work now when all you did was to replace sudo command with sudo and a space? The answer lies in the way alias is designed to be used.
If you refer to the alias part of the bash manual, you’ll see that the first word of each simple command, if unquoted, is checked to see if it has an alias. If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion.
In other words, in a command only the first word is checked for alias. But if the alias value has a space or tab in the end, the next word of the command is also checked for an alias.
This is why when you simply run sudo my_alias command with sudo being aliased to ‘sudo ‘, first the sudo is checked for alias. An alias is found with space at its end and thus your system checks the next word for an alias. It finds the alias for this one as well and your aliased command works as you want it to be.
I hope you liked this quick little tip helpful in running alias with sudo. Any questions or suggestions are always welcomed.