100 Useful Command-Line Utilities

by Oliver; 2014

22. sudo

Based off of An Introduction to the Command-Line (on Unix-like systems) - sudo and the Root User: sudo and the Root User sounds like one of Aesop's Fables, but the moralist never considered file permissions and system administration a worthy subject. We saw above that, if you're unsure of your user name, the command whoami tells you who you're logged in as. If you list the files in the root directory:
$ ls -hl /
you'll notice that these files do not belong to you but, rather, have been created by another user named root. Did you know you were sharing your computer with somebody else? You're not exactly, but there is another account on your computer for the root user who has, as far as the computer's concerned, all the power (read Wikipedia's discussion about the superuser here). It's good that you're not the root user by default because it protects you from yourself. You don't have permission to catastrophically delete an important system file.

If you want to run a command as the superuser, you can use sudo. For example, you'll have trouble if you try to make a directory called junk in the root directory:
$ mkdir /junk
mkdir: cannot create directory ‘/junk’: Permission denied
However, if you invoke this command as the root user, you can do it:
$ sudo mkdir /junk
provided you type in the password. Because root—not your user—owns this file, you also need sudo to remove this directory:
$ sudo rmdir /junk
If you want to experience life as the root user, try:
$ sudo -i
Here's what this looks like on my computer:
$ whoami	# check my user name
oliver
$ sudo -i	# simulate login as root
Password:
$ whoami	# check user name now
root
$ exit		# logout of root account
logout
$ whoami	# check user name again
oliver
Obviously, you should be cautious with sudo. When might using it be appropriate? The most common use case is when you have to install a program, which might want to write into a directory root owns, like /usr/bin, or access system files. I discuss installing new software below. You can also do terrible things with sudo, such as gut your whole computer with a command so unspeakable I cannot utter it in syntactically viable form. That's sudo are em dash are eff forward slash—it lives in infamy in an Urban Dictionary entry.

You can grant root permissions to various users by tinkering with the configuration file:
/etc/sudoers
which says: "Sudoers allows particular users to run various commands as the root user, without needing the root password." Needless to say, only do this if you know what you're doing.

<PREV   NEXT>