Learning Command Line - The Sudo Command

Posted on Aug 07, 2018

Grant root access to your command line operation with sudo.

Let’s talk about sudo command, which is used to give your action a superuser authority. From your terminal, type this command:

$ cd / && ls -ld opt
drwxr-xr-x 1 root root 4096 May 10 15:14 opt

Can you see the “root root” name where our username used to be? This means that the directory is owned by the root user — or superuser, they are the same — and can only be operated using superuser authority, or sudo. Type this command in your terminal

$ mkdir opt/my_directory
mkdir: cannot create directory ‘opt/my_directory’: Permission denied

You can’t create any directory inside opt directory because that directory is owned by root, and a normal user can’t do anything with it. The sudo command will elevate your user status, and for the duration of the command you give to the terminal, your current user will be “root” itself. Don’t forget to enter your password, the one you used for login.

$ sudo mkdir opt/my_directory
[sudo] password for ubuntu:
$ ls -la opt
drwxr-xr-x 1 root root 4096 Aug  5 19:11 .
drwxr-xr-x 1 root root 4096 Aug  4 01:13 ..
drwxr-xr-x 1 root root 4096 Aug  5 19:11 my_directory

As you can see, the my_directory is owned by root and not nathan (or your username). The sudo command and “root” superuser was invented to prevent any important commands from being processed without permission.

For example, we’ve learned about rm -rf from the previous chapter. If you went into the root directory in cd / and then type sudo rm -rf /*, it will remove all important filesystems, doing a critical damage to your computer’s system to the point where you need to reinstall your OS and format the computer harddisk. I haven’t tried it, and you shouldn’t either!

$ sudo rm -rf /*
#Never do this!!!!

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.