Command-Line Basics
local graph
Chapter 2 — Command-Line Basics
Section titled “Chapter 2 — Command-Line Basics”In this chapter, we’re going to dive right into the Linux command line. We will explain what makes it so powerful and, by extension, important to every system administrator and DevOps person. But more importantly, we will start teaching you the most useful commands and a way to use them efficiently. Along the way, we will be adding other core Linux concepts, as they will be required to understand the chapter.
In this chapter, we’re going to cover the following main topics:
- What a command line is and how it works
- Why it is so important to feel comfortable working with the command line
- Basic commands for Linux system administration
It is not possible to introduce all the commands and tools in a single chapter. What follows is our choice of the most basic tools you will need to know. Managing the Linux system is a separate book topic on its own. It so happens that Packt does have several publications on that.
Technical requirements
Section titled “Technical requirements”It is highly recommended to have a Linux system installed and ready for use. We recommend it to be a virtual machine or a laptop that you can safely reinstall from scratch in case something goes horribly wrong. It will let you follow the examples in the book and perform any kind of exercise that we give you.
We are not going to cover an installation. Every distribution may use its own installer, either graphical or text (depending on the distribution and which variant you’ve picked). You’ll need to note down or remember the name of your user (conveniently called username or login) and password. There are ways to get into the system if you have physical access and you don’t know either the login or password, or both, but they are way outside of the scope of this book.
Our main distribution in the book is Debian. However, you should be alright with any of the major ones we covered in the previous chapter, Choosing the Right Linux Distribution, as long as it isn’t Alpine.
The Linux command line – shell
Section titled “The Linux command line – shell”The natural environment for a Linux system administrator is the command line. You’ll never hear anyone call it that, however. The correct name is the shell, and from now on, that’s how we’re going to address it in the book.
The shell is a program that accepts input from a user (mostly keyboard strokes, but there are other ways, and you can even use a mouse pointer), interprets it, and, if it’s a valid command, executes it, providing the user with the result or with error information if they’ve made a mistake or if the commands couldn’t complete their execution properly.
There are a few ways to access the shell:
- Log in to the Terminal (screenshot in Figure 2*.1*)
Note
You’ll also see the term console. There is a difference between the Terminal and a console. A console is a physical device that lets users interact with the computer. It is the physical input (nowadays, mostly keyboard) and output (nowadays, a monitor, but in the beginning, the output was printed out). Terminal is a console emulator, a program that lets users perform the same tasks.
- Open a Terminal window in a graphical interface, if you have one
- Log in remotely over a secure connection from another device (phone, tablet, or your computer)
The shell is a very powerful environment. It may seem cumbersome at first to do everything by typing commands, but soon you’ll learn that the more complex the task, the more you can do with the shell, more easily than with graphical interfaces. Every Linux system administrator worth their salt will know how to do tasks in the shell and how to manage the system through it, and I wouldn’t risk much by betting that they will prefer the shell to any GUI.
Getting to know your shell
Section titled “Getting to know your shell”The shell is a program, and as such, there is not a single shell. Instead, there are a number of more or less popular shells that bring forth their own view on how things should be done.
By far the most popular and default in most Linux distributions is Bash (Bourne again shell). There are other shells you may want to be aware of:
- sh: The original Steve Bourne shell. It is the shell, the very first one ever written that we know of. While it lacks many interactive features that users came to appreciate from other, more modern shells, sh is known for its speed of script execution and small size.
- ksh: Developed as an evolution of the Bourne shell, it is a superset of its predecessor. Thus, all scripts written for sh will run in ksh.
- csh: The C shell. The name comes from its syntax, which closely follows the C programming language.
- zsh: The Z shell. It should be well known to macOS users, as it is a default on this operating system. It is a completely modern shell, providing a lot of features that you’d expect from it: command history, arithmetic operations, command completion, and so on.
We won’t trouble you much with shell variants and history. If you are interested in how Bash came to be, refer to this Wikipedia article: https://en.wikipedia.org/wiki/Bash_(Unix_shell).
In our book, we are working with Bash. As mentioned earlier, it is the default shell for most Linux distributions, it offers sh compatibility mode, it has all the features you’d expect from a modern shell, and the amount of books, articles, how-tos, and other material for extending your knowledge about it is staggering.
The first task that we will be performing is logging in to your shell. Depending on your chosen installation method, you may need to power up the local virtual machine, your physical machine, or a cloud-based Virtual Private Server (VPS). If you have picked a server installation without a graphical user interface, you should see something similar to the following screenshot:

Figure 2.1 – Login screen
You are presented with a login screen, where you can provide your username and password. Once successfully logged in, you are presented with a command prompt, which confirms that you’ve just successfully started your shell.
The way the prompt looks is configurable and may be different depending on your chosen distribution. There is, however, one thing that will stay the same, and we advise you to never change it. In the world of Linux, there are two types of users: normal users and the superuser. While the login for normal users can be anything as long as it adheres to the Linux user naming conventions, the superuser is called root. To log in to the root account, you’d type in root as the username/login and its password next.
The superuser account is named that way for a reason. In most Linux distributions, it’s the omnipotent user. Once logged in as root, you can do anything you wish, even deleting all files, including the operating system itself.
To help you distinguish between being a normal user and the root one, the prompt will present you with a clue. While logged in as root, your prompt will end with the # sign. When logged in as a normal user, it will present you with $.
While we’re at it, the # (hash) sign is also a so-called comment sign. If you happen to paste a command or type it from the internet, if it starts with # or $, it is your clue as to which type of user should run this command. You should omit this sign, especially as # in front will prevent the command from running.
In addition to the sign that ends the prompt, many distributions will prepend the username to it, making sure you know which user you are. Given a user admin on a Linux system called myhome, the default prompt for Debian 11 will look like this:
$admin@myhome:~$For the root user, it would look like this:
root@myhome:~#For the record, there are more ways to check your identity, but we will leave that for Chapter 4.
I call to thee
Section titled “I call to thee”So far, so good. You have logged in, you know who you are, you can type, and you can read. But how do you actually run programs?
In the Linux lingo, running a program is executing it or calling it. Actually, calling is mostly used when referring to system commands or shell built-in commands, and executing is used when talking about something that is not a part of the distribution—so-called third-party programs or binary.
Before I can tell you how to execute a program or call a command, I’ll have to explain a little bit about filesystem structure and a very important system variable called PATH.
The filesystem structure
Section titled “The filesystem structure”Since it may be your first time, we are going to step back a little bit and explain how the filesystem is structured (in other words, how directories are organized in typical Linux).
Linux follows the Unix philosophy that states that everything is a file. (There are exceptions, but not many.) The consequence is that almost every aspect of the operating system is reflected either as a file or a directory. Memory states, processes’ (running programs) states, logs, binaries, and device drivers all live within this structure. This also means that almost every aspect of your Linux system can be edited or inspected using just normal text editing tools.
In the directory tree, its structure always starts with a / folder, called the root directory. Every drive, network share, and system directory lives in a hierarchy that starts from the root.
The process of making a network share or local drive available to the system or user is called mounting and the resource that is made available is mounted. Remember that word, as we’re going to be using it from now on. Different from Microsoft Windows, where your drives appear as a separate letter with each being its own root directory, in Linux, your hard drive will be mounted somewhere within the directories hierarchy. As an example, the user home directory can be stored on a separate hard drive, mounted under the /home/ directory. You would never be able to tell it when browsing the filesystem structure. The only way to tell would be to inspect mounted drives and partitions using the following commands:
$ mountor
$ dfWe are going to elaborate on them in Chapter 3, so for now, just know they exist.
The name of the uppermost directory is /. We already covered that. The separator between folders nested in another folder is also /. So /usr/bin means a bin directory that exists in the usr directory, and the usr directory exists in the / directory. Simple.
There is a very nice command that lets us inspect the directory structure, conveniently called tree. It may not be present in your system. If so, don’t be worried; it’s not so important that you run it rather than go through our explanation. In Chapter 3, when we introduce the installation of packages, you can revisit and play around. By default, the tree command will flood your screen with the full hierarchy, making it difficult to read and follow. There is an option, however, that lets us limit the depth we will be inspecting:
admin@myhome:~$ tree -L 1 //|-- bin -> usr/bin|-- boot|-- dev|-- etc|-- home|-- lib -> usr/lib|-- lib32 -> usr/lib32|-- lib64 -> usr/lib64|-- libx32 -> usr/libx32|-- lost+found|-- media|-- mnt|-- opt|-- proc|-- root|-- run|-- sbin -> usr/sbin|-- srv|-- sys|-- tmp|-- usr\`-- var22 directories, 0 filesThere are several important concepts to cover here; we won’t be explaining all the directories at this time, however. The first time a given folder becomes important, in Chapter 3 onward, we will briefly touch upon it.
First, the calling of tree. You saw my prompt, which tells me I am running as user admin, on a system named myhome and that I am not a root user (the dollar sign at the end). If you want to run the tree command, you will skip the prompt. Next is the actual call: tree with the -L option and number 1; this instructs the program to only print one level of depth. In other words, it will not go any deeper into the directories. Finally, the / symbol tells the program to start printing at the very beginning of the filesystem—the root folder.
Next, you’ll notice that some rows have this mysterious arrow pointing from one name to another. This denotes a shortcut. There are two types of shortcuts, hard and symbolic. Directories can only have a symbolic link. In the preceding output, the /bin directory is a link to a /usr/bin directory. For all intents and purposes, they can be treated as one. There are technical and historical reasons for the existence of this link. In days past, tools living in /bin and /sbin were used to mount a /usr partition and then allow access to /usr/bin and /usr/sbin. Nowadays, this task is handled earlier in the boot process by other tools and the requirement is no longer necessary. The structure is kept for backward compatibility with tools that may require the existence of both /bin and /sbin directories. More details can be found at https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html or https://www.linuxfoundation.org/blog/blog/classic-sysadmin-the-linux-filesystem-explained.
Since we already touched on the /bin and /sbin directory, let’s explain the difference. The /usr/bin directory contains binaries —in other words, commands that can be of interest to every user in the system. The /usr/sbin directory contains so-called system binaries. Those are commands that should concern only the root user. It will also contain binaries for system processes (called daemons)—programs that run in the background and do important work for the running system.
The /root directory is the home of the superuser. This is where all its configuration files lay.
The interesting one is the /home directory. This is where all the user home directories exist. When I created my admin user for my home machine, it was placed in the / home/admin folder.
Of importance to us at this moment will also be the /etc/ directory. It contains all the configuration files for the whole system: the source for online package repositories, default shell configuration, system name, processes that start at the boot, system users and their passwords, and time-based commands. On a freshly installed Debian 11 system, the /etc/ directory contains about 150 subdirectories and files, and each subdirectory may contain more folders inside.
The /tmp folder contains temporary files. They only live when the system is booted and will be deleted the moment it is shut down or restarted. The nature of those files is often very volatile; they can hop into existence and disappear very fast or can be modified very often. It is not uncommon for this directory to only exist in the computer’s RAM. It’s the fastest storage device your system has and will automatically purge on restart or power off.
As mentioned earlier, additional drives are mounted under this structure. We could have a separate hard drive for home directories. The whole /home folder may live on it or even on a networked hard disk array. As mentioned, the /tmp directory is often mounted in the RAM. Sometimes, the /var directory (which contains things that can change often in the system but are not supposed to be purged, such as logs) is mounted on a separate drive. One of the reasons is that the contents of /var, and especially of /var/log (where the system logs live), can grow very fast and take all the available space, making accessing the system impossible or very tricky.
Finally, there are two important and special directories that exist everywhere you go:
.: A single dot means the current directory. If you choose to go to a.folder, you’ll end up where you are. It’s useful, however, as you’ll see in Chapter 3...: Two dots mean the directory above us—the parent directory. If you choose to go to a..folder, you’ll end up one level above where you started. Note that for the/directory, both.and..mean the same:/. You can’t go any higher than the root.
Running a program
Section titled “Running a program”Now that we know some things about the folder hierarchy, let’s briefly touch on executing programs.
There are three basic ways to execute a program in a shell:
- Call it by its name: This requires that it is placed in a directory that is in a
PATHvariable (explained in Chapter 3). - Call it by an absolute path: The absolute path starts with
/. When using the absolute path, you have to list all the directories that lead to the program, including the leading/. An example execution may look like this:
/opt/somecompany/importantdir/bin/program- Call it by a relative path: This will not start with a dot or two dots. This way of executing a program requires that you know where in the filesystem you are and where in the filesystem this program is. It’s useful if you are in the same directory as the binary or very close to it:
- To call a program in the same directory as your user, you precede it with a dot and a slash:
./. This shortcut means the current directory. A sample call could look like./myprogramor./bin/myprogram. The latter would mean: let’s start a program calledmyprogramthat is in abindirectory that is in the current directory.- To call a program in a directory somewhere else in the system using a relative path, we will have to use the two dots, meaning the parent folder. Let’s say you are logged in to your home directory,
/home/admin, and want to execute a program in/opt/some/program/bin; you’d call../../opt/some/program/bin/myprogram. The two dots and slash mean moving up.
- To call a program in a directory somewhere else in the system using a relative path, we will have to use the two dots, meaning the parent folder. Let’s say you are logged in to your home directory,
- To call a program in the same directory as your user, you precede it with a dot and a slash:
If this looks arcane, it is because it is a little bit. Fortunately, everything will start coming together as the book progresses.
The command to teach you all commands
Section titled “The command to teach you all commands”You should get into the habit of searching the internet whenever you have a question or problem. Most of the issues you are going to run into are already fixed or explained out there. However, there’s one command that can save your life—or at least lots of time. You should make another habit of using it often – even if you are sure you know the correct syntax, you might just discover a better way of completing your task. This command is as follows:
$ manThe man command is a shorthand for manual and it is exactly what it says: it is a manual for whatever command you want to learn about. To learn more about the man command, simply call the following:
$ man manThe output you’ll see should be similar to the following:
MAN(1) Manual pager utils MAN(1)NAME man - an interface to the system reference manualsSYNOPSIS man [man options] [[section] page ...] ... man -k [apropos options] regexp ... man -K [man options] [section] term ... man -f [whatis options] page ... man -l [man options] file ... man -w|-W [man options] page ...DESCRIPTION man is the system's manual pager. Each page argument given to man is normally the name of a program, utility or function. The manual page associated with each of these arguments is then found and displayed. A section, if provided, will direct man to look only in that section of the manual. The default action is to search in all of the available sections following a pre-defined order (see DEFAULTS), and to show only the first page found, even if page exists in several sections.I have cut it for brevity. A well-written man page will have several sections:
name: This is where the name of the command is stated. If the command exists under various names, they will all be listed here.synopsis: This will list possible ways of calling the command.description: This is the purpose of the command.examples: This will show several examples of the command call, to make the syntax clearer and give some ideas.options: This will show all the available options and their meaning.getting help: This is how to get a shortened version of the command synopsis.files: If the command has configuration files or consumes files known to exist in the filesystem, they will be listed here (forman, I have listed/etc/manpath.configand/usr/share/man).bugs: This is where to look for bugs and report new ones.history: This will show all the current and previous authors of the program.see also: These are programs that are in some way tied to the command (forman:apropos(1),groff(1),less(1),manpath(1),nroff(1),troff(1),whatis(1),zsoelim(1),manpath(5),man(7),catman(8), andmandb(8)).
Many commands will contain a lot of additional sections, specific to this program.
The man pages will contain a lot of knowledge, and sometimes the names will duplicate. This is where the mysterious numbers in brackets come into play. The man pages are broken down into sections. To quote the man page about man:
- Executable programs or shell commands
- System calls (functions provided by the kernel)
- Library calls (functions within program libraries)
- Special files (usually found in
/dev) - File formats and conventions, for example,
/etc/passwd - Games
- Miscellaneous (including macro packages and conventions), for example,
man(7),groff(7) - System administration commands (usually only for
root) - Kernel routines [non-standard]
Let’s take, for example, printf. There are several things that are called printf. One of them is a library function of the C programming language. Its man page will live in section 3.
To read about that library function, you have to tell man to look into section 3:
admin@myhome:~$ man 3 printfPRINTF(3) Linux Programmer's Manual PRINTF(3)NAME printf, fprintf, dprintf, sprintf, snprintf, vprintf, vfprintf, vdprintf, vsprintf, vsnprintf - formatted output conversionIf you don't, what you'll get is a shell function for printing—totally useless in C programming:admin@myhome:~$ man printfPRINTF(1) User Commands PRINTF(1)NAME printf - format and print dataSYNOPSIS printf FORMAT [ARGUMENT]... printf OPTIONMost commands and shell programs have a shorter synopsis called help. Usually, it can be invoked by running binary with the -h or — help option:
admin@myhome:/$ man --helpUsage: man [OPTION...] [SECTION] PAGE... -C, --config-file=FILE use this user configuration file -d, --debug emit debugging messages -D, --default reset all options to their default values --warnings[=WARNINGS] enable warnings from groffI have cut the output for brevity, but you get the drift.
Note
The short options are preceded with one dash while longer ones are preceded with two. — help is not one long dash but two standard ones.
The man and –help commands should become your friends even before searching online. A lot of questions can be quickly answered just by looking at the help output. Even if you are a seasoned administrator, you are allowed to forget command syntax. There is an online source of endless Linux guides called The Linux Documentation Project: https://tldp.org. Make it your bookmark.
Know your environment
Section titled “Know your environment”The way your system behaves is controlled by several factors. One of them is a set of variables called environment. They set things such as what language your system is going to use when talking to you, how entries during listing will be sorted, where the shell is going to look for executables, and many more. The exact set of variables depends on the distribution.
The full set of all the environment variables that your shell has set can be printed using the env command:
admin@myhome:/$ envSHELL=/bin/BashPWD=/LOGNAME=adminXDG_SESSION_TYPE=ttyMOTD_SHOWN=pamHOME=/home/adminLANG=C.UTF-8PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/gamesIf you know the variable you want to inspect, you can use the echo command:
admin@myhome:/$ echo $PATH/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/gamesNotice that when you are using a variable, you have to precede its name with a dollar sign, hence $PATH.
Where in the PATH am I?
Section titled “Where in the PATH am I?”Since we mentioned PATH, let’s talk briefly about it. Path can mean two things:
- A place in the system that leads to something: a binary, a file, or a device
- An environment variable that lists places where the shell is going to look when trying to execute a program
You already know a little bit about the first kind of path. We explained the absolute path and relative path. There is a command that lets you move around, and it’s called cd (shortcut for change directory). If you call cd without an argument, it will take you to your home directory. If you call it with an argument, it will move you to the specified folder, given that it exists, you specified the path properly, and you have the right to access it. Let’s see a few examples:
- Checking which directory we’re currently in:
admin@myhome:~# pwd/home/admin- Changing directory to
/home/admin/documents/current:
admin@myhome:~# cd documents/currentadmin@myhome:~/documents/current#- Changing one directory up from a current level:
admin@myhome:~/documents/current# cd ..admin@myhome:~/documents#- Changing the directory to the user home directory:
admin@myhome:~/documents# cdadmin@myhome:~# pwd/home/adminKnow your rights
Section titled “Know your rights”The most basic security mechanism in Linux is based on defining a combination of rights for a set of entities. The rights are as follows:
readwriteexecute(read contents when talking about a directory)
And the entities are as follows:
- The owner of the file or directory
- The group that owns the file or directory
- All the other users and groups
This is a crude security system. It’s sufficient for small servers and desktop uses but, for more complex setups, it is sometimes too restraining. There are other additional systems, such as Access Control Lists (ACLs), AppArmor, SELinux, and more. We are not going to cover them in this book.
With the use of the previous systems, we can still achieve quite a lot regarding our system security.
How do those rights and ownership work? We use the ls command (list files and directories):
admin@myhome:/$ ls -ahltotal 36Kdrwxr-xr-x 3 admin admin 4.0K Aug 20 20:21 .drwxr-xr-x 3 root root 4.0K Aug 20 14:35 ..-rw------- 1 admin admin 650 Aug 20 20:21 .Bash_history-rw-r--r-- 1 admin admin 220 Aug 4 2021 .Bash_logout-rw-r--r-- 1 admin admin 3.5K Aug 20 14:47 .Bashrc-rw-r--r-- 1 admin admin 0 Aug 20 14:40 .cloud-locale-test.skip-rw------- 1 admin admin 28 Aug 20 16:39 .lesshst-rw-r--r-- 1 admin admin 807 Aug 4 2021 .profiledrwx------ 2 admin admin 4.0K Aug 20 14:35 .ssh-rw------- 1 admin admin 1.5K Aug 20 14:47 .viminfoThe output is presented in nine columns.
The first column presents the type of the entry and the rights in a concise manner, but let’s jump to the third and fourth. Those columns inform us about who is the owner of the file and what user group the file belongs to. All files and directories must belong to a user and to a group. In the preceding output, most of the files belong to the user admin and to the group admin. The exception is the .. directory, which belongs to the root user and root group. It is common to denote this pair in the form user:group.
The next columns describe the size (with a directory, it describes the size of the entry, not how much space the directory contents take), the date of the last change, the time of the last change, and the name of the entry.
Now, let us go back to the first column. It informs us what an owner, a group, and all other users in the system are allowed to do with the given file or directory:
- The letter
dmeans that we are dealing with a directory. A dash (–) means it’s a file. - Next is a group of nine one-letter symbols that denote who can do what with the given entry:
The first three letters denote what the file or directory owner can do with it. r means that they can read it, w means they can write to it, and x means they can execute it as a program. In the case of a text file with x set, the shell will try to run it as a script. The caveat is when we are dealing with a directory. x means that we can change a current working directory to it. It is possible to be able to go into a directory (x set) and not be able to see what is in it (r not set).
The same three letters explain the group rights in the second grouping.
The same set explains all other users’ rights in the third grouping.
In the preceding output, .Bash_history is a file (it has a dash in the first field); the owner of the file (user admin) can read from it and write to it. It is possible to be able to write to a file (for example, a log file) but not be able to read from it. The file cannot be executed as a script (a dash). The next six dashes inform us that neither users assigned to the group admin nor any other user or group in the system can do anything with this file.
There is one exception, and it is the root user. Without stepping up with ACLs and tools such as SELinux, you cannot limit root’s omnipotence in the system. Even for a file or directory that has no rights assigned (all dashes), root has full access to it.
The administration of the ownership and the rights is done by means of two commands:
chown: This command allows you to change the ownership of a file or directory. The name is a shortcut for changing owners. The syntax is quite simple. Let’s take this opportunity to exercise a bit with the notation in Linux help:
chown [OPTION]... [OWNER][:[GROUP]] FILE...There is an unwritten convention that most, if not all, commands’ help adhere to:
- Text without any brackets must be typed as shown.
- Anything inside
[ ]brackets is optional. In thechowncommand, the user and group are optional, but you must supply at least one. - Text in
< >brackets is mandatory but is a placeholder for whatever you will have to supply. - Brackets
{ }denote a set of options and you’re supposed to choose one. They can be separated by a vertical line,|. - Three dots after an element means this element can be supplied multiple times. In the
chowncase, it’s the name of the file or directory.
The following is a set of ownership changes that I apply to a file:
- I change the ownership from
admintotestuser, but I leave the group unchanged. Please note that changing actually requires the use of therootaccount (via thesudocommand, explained in Chapter 3). - I change the ownership back to
admin, but change the group totestuser:
admin@myhome:~$ ls -ahl testfile-rw-r--r-- 1 admin admin 0 Aug 22 18:32 testfileadmin@myhome:~$ sudo chown testuser testfileadmin@myhome:~$ ls -ahl testfile-rw-r--r-- 1 testuser admin 0 Aug 22 18:32 testfileadmin@myhome:~$ sudo chown admin:testuser testfileadmin@myhome:~$ ls -ahl testfile-rw-r--r-- 1 admin testuser 0 Aug 22 18:32 testfileIn the preceding output, we can see that a successful call to a command produces no output (chown) unless the output is the purpose of the command (ls). This is one of the basic rules that Linux follows. In the following output, we can see what happens when the command terminates with an error—insufficient rights to change the group:
admin@myhome:~$ chown :testuser testfilechown: changing group of 'testfile': Operation not permittedOne other way to run the chown command is to point to a reference file, as in the following example:
admin@myhome:~$ sudo chown —reference=.Bash_history testfileadmin@myhome:~$ ls -ahl testfile-rw-r—r—1 admin admin 0 Aug 22 18:32 testfileadmin@myhome:~$ ls -ahl .Bash_history-rw------- 1 admin admin 1.1K Aug 22 18:33 .Bash_historyUsing the –reference option, we point to a file that will be a matrix for our changes. This will become more interesting once we move on to the next chapter.
chmod: Similar to thechowncommand,chmod(short for change mode) is the one you’ll be looking for to change the rights of the assigned user and group:
admin@myhome:~$ chmod --helpUsage: chmod [OPTION]... MODE[,MODE]... FILE... or: chmod [OPTION]... OCTAL-MODE FILE... or: chmod [OPTION]... --reference=RFILE FILE...The chmod command will accept options, mandatory mode, optionally more modes, and a list of files that the change is supposed to be applied to. As with the chown command, we can specify a reference file that will have its mode copied over.
In the first form, you will specify the mode for either a user, a group, others, or all of them using the following syntax:
chmod [ugoa…] [-+=] [perms…] FILE...Here, the following meanings apply:
u: User, in other words, the owner of the fileg: Group that owns the fileo: Others—all othersa: All, meaning everyone-: Remove the specified right+: Add the specified right=: Make the rights exactly as specified
Let’s see some examples.
This adds read and write permissions to the testfile file for the file owner:
chmod u+rw testfileThis removes the execute right to the testfile file for everyone who is not the file owner and is not in the group that owns the file:
chmod o-x testfileThis gives the user and the group read and execute rights to the testfile file:
chmod ug=rx testfileIn the syntax summary we have pasted, the middle row is interesting. The octal mode means that we can specify the mode by means of numbers. This is especially useful in scripts, as dealing with numbers is easier. Once you memorize the mode numbers, you may find it easier to use the octal chmod.
The formula for the numeric setting of file mode is simple:
0: no rights (---)1: execute mode (--x)2: write mode (-w-)4: read mode (r–)
To set the mode on a file or directory, you will use a sum of the rights you want to apply, starting with a leading 0, which will inform chmod that you are setting octal mode. The syntax is as follows:
chmod [OPTION]... OCTAL-MODE FILE...There is a very important difference between this form and the letter one—you must specify the mode for all three types of entities: user, group, and others. You cannot omit any of them. This means that you also won’t be using the -, +, or = signs. With the octal syntax, the rights will always be exactly as specified.
To combine the modes, you will add their numbers and use the sum as the final specifier. You will find that this is a very elegant solution. There are no two identical sums of those numbers (combination of rights). Try it:
- Execute and read is 1 and 2 = 3. There is no other combination of the modes that can result in 3.
- Read and write is 2 and 4 = 6. Again, no other combination can result in 6.
Now, let’s try some examples.
The owner of the file will have read and write access to the file, while the group and others will have read access:
chmod 0644 testfileThe owner of the file has all the rights (read, write, and execute), while the group and others can read and execute only:
chmod 0755 testfileThe leading 0 in the mode is not obligatory.
We have covered the filesystem, directory structure, and basic file permissions related to users and groups. In the next section, we will introduce basic Linux commands.
Interacting with the system
Section titled “Interacting with the system”Programs and scripts lying on a hard drive are just files. The moment they get mapped to the memory and start performing their function, they become processes. At this stage, you can safely assume that anything running in the system is some kind of a process.
Process this
Section titled “Process this”Processes in Linux have several characteristics that you need to be aware of:
- Process ID (PID): A system-wide unique numerical identifier.
- Parent process ID (PPID): Every single process in the Linux system, except process number 1, has a parent. Process number 1 is an init process. It is the program responsible for starting all the system services. A program that starts another program is known as a parent. A program started by another program is known as a child. When you log in to the system, your shell is a process too, and it has its PID. When you start a program in that shell, your command-line PID will become the parent ID of that program. If a process loses its parent (i.e., the parent process terminates without terminating its child), then the child process is assigned a new parent: process number 1.
- State: There are five states that a process can be in:
- R: Runnable or running. There is a distinction between running and runnable, but in the statistics, they are grouped together. A running process is one that actively takes CPU time and resources. It is being executed as we speak. A runnable process is one that has been put aside while another process takes its place. This is how single-core computers create the illusion of multitasking—executing many programs at once; they rotate every started program on the CPU in time slices that are so short that humans can’t notice when the program is actually being executed on the CPU and when it is waiting in the queue.
- S: Interruptible sleep. A program may request an additional resource besides RAM and CPU time. If it needs to wait for the resource to become available, then it goes into a separate queue and sleeps. This program will awake when the required resource is available and can be interacted with using interrupts—special kinds of signals. We will cover signals in Chapter 3.
- D: Uninterruptible sleep. As with the preceding
Sstate, the process went to sleep. It will not, however, accept any interrupts and signals. It will only awake when a requested resource becomes available. - T: We can instruct a program to stop its execution and wait. This is called a stopped state. Such a process can be brought back to execution with the use of a special signal.
- Z: Zombie. When a process ends its execution, it informs its parent process about that. The same happens when the process is terminated. The parent is responsible for removing it from the process table. Until it happens, the process remains in a zombie state, also called defunc.
- R: Runnable or running. There is a distinction between running and runnable, but in the statistics, they are grouped together. A running process is one that actively takes CPU time and resources. It is being executed as we speak. A runnable process is one that has been put aside while another process takes its place. This is how single-core computers create the illusion of multitasking—executing many programs at once; they rotate every started program on the CPU in time slices that are so short that humans can’t notice when the program is actually being executed on the CPU and when it is waiting in the queue.
- User: The owner of the process, or rather, a user with whose system rights the process is being executed. If that user cannot do something, the process cannot do it either.
- CPU: Percentage of the CPU time the process is using, presented as a floating-point number between 0.0 and 1.0.
- MEM: The memory usage, again between 0.0 and 1.0, where 1.0 is 100% of system memory.
Each process has more characteristics than the ones we’ve just covered, but those are absolutely essential. Managing processes is a subject for a separate chapter, if not an entire book.
The tool to inspect the processes is called ps. It seems like a pretty simple command at first sight, but in reality, the man page shows an incredible amount of options. It is important to note that ps itself will only print a snapshot of the system. It won’t be monitoring and updating its output. You can combine ps with watch or run top or htop commands to have continuous information about the processes and system load.
In its simplest form, ps will print all processes running with the same user ID as the user that calls it:
admin@myhome:~$ ps PID TTY TIME CMD 24133 pts/1 00:00:00 Bash 25616 pts/1 00:00:00 psOn my Linux machine, there are only two processes running for my user: the Bash shell and the ps program itself.
The ps command has several interesting options that help interrogate the system about the running processes. Now, specifying options to ps is tricky, because it accepts two syntaxes, one with a dash and one without, and some options have different meanings depending on the dash. Let me quote the man page:
1 UNIX options, which may be grouped and must be preceded by a dash. 2 BSD options, which may be grouped and must not be used with a dash. 3 GNU long options, which are preceded by two dashes.Note that ps -aux is distinct from ps aux. The POSIX and UNIX standards require that ps -aux print all processes owned by a user named x, as well as printing all processes that would be selected by the -a option. If the user named x does not exist, this ps may interpret the command as ps aux instead and print a warning. This behavior is intended to aid in transitioning old scripts and habits. It is fragile, subject to change, and thus should not be relied upon.I have cut some output for brevity. This distinction may become important once you start working with shell scripts, as they may adopt any of the three syntaxes. Whenever in doubt, use the dash notation:
-f: So-called full output. It will print the ID of the user that runs the command,PID,PPID, CPU utilization (C), start time of the process (STIME), terminal (TTY) to which it is attached, how long it has been running (TIME), and the command that started the process:
admin@myhome:~$ ps -fUID PID PPID C STIME TTY TIME CMDadmin 24133 24132 0 16:05 pts/1 00:00:00 -Bashadmin 25628 24133 0 17:35 pts/1 00:00:00 ps -f-e: All processes of all users:
admin@myhome:~$ ps -e PID TTY TIME CMD 1 ? 00:00:04 systemd 2 ? 00:00:00 kthreadd[...] 25633 ? 00:00:00 kworker/u30:0-events_unbound 25656 pts/1 00:00:00 ps-ef: To see all processes in the long output format:
admin@myhome:~$ ps -efUID PID PPID C STIME TTY TIME CMDroot 1 0 0 Aug20 ? 00:00:04 /sbin/initroot 2 0 0 Aug20 ? 00:00:00 [kthreadd]-ejH: A nice process tree. The more indented CMDs (the last column of the output) are children of the less indented ones:
admin@myhome:~$ ps -ejH PID PGID SID TTY TIME CMD 2 0 0 ? 00:00:00 kthreadd 3 0 0 ? 00:00:00 rcu_gp 4 0 0 ? 00:00:00 rcu_par_gp 6 0 0 ? 00:00:00 kworker/0:0H-events_highpri 9 0 0 ? 00:00:00 mm_percpu_wqThere are many more options available, especially to control which fields are of interest. We will come back to them in later chapters.
There is a command that has a name that can be very misleading, the kill command. It is used to send so-called signals to the running processes. Signals are a way of telling processes to perform a kind of action. One of them actually kills the program, terminating it at once, but that’s just one of many.
To list existing signals, use the kill - l command:
admin@myhome:~$ admin@myhome:~$ kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR111) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+338) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+843) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+1348) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-1253) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-758) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-263) SIGRTMAX-1 64) SIGRTMAXOkay, this list is cute, but it tells us nothing. How can we tell what each of those signals does? Here’s a bit of detective work. First, since we see those in the kill -l output, let’s invoke the man kill command and see whether there’s anything that can explain them to us:
EXAMPLES kill -9 -1 Kill all processes you can kill. kill -l 11 Translate number 11 into a signal name. kill -L List the available signal choices in a nice table. kill 123 543 2341 3453 Send the default signal, SIGTERM, to all those processes.SEE ALSO kill(2), killall(1), nice(1), pkill(1), renice(1), signal(7), sigqueue(3), skill(1)There is an examples section that shows and describes one signal, but in the SEE ALSO section, we can see a reference to a man page signal in section 7. Let us check it out:
admin@myhome:~$ man 7 signalSIGNAL(7) Linux Programmer's Manual SIGNAL(7)NAME signal - overview of signalsNow, there’s a nice page with a table listing all signals available to you in Linux.
So, how do you use this kill command? Do you have to learn about all these signals? The answer is no. There are a handful of signals that you’ll be using. And if you forget any, don’t hesitate to man them or search the web:
kill -9 PID: The infamousSIGKILL. This terminates the process whose PID we have specified abruptly, forcing it to omit any cleanup it may do normally. If it has opened file handles, it won’t free them; if it has to write any information to a file or synchronize with another program, it won’t do it. This should be used sparingly, only when we are sure that we really have to stop a program from running.kill PID: If no signal is specified, then by default,SIGTERMis sent. This tells the program to stop running but gracefully—perform all the exit routines and cleanup it needs. If you have to use thekillcommand, this is the preferred use.kill -1: The so-calledSIGHUPsignal. It was originally used for detecting loss of user connection—hangup of the phone line. Currently, it is often used to tell the process to reread its configuration.
Here is an example of calling kill to terminate a process. I have started a shell script that does nothing except wait for a keyboard input. I called it sleep.sh:
admin@myhome:~$ ps aux | grep sleepadmin 24184 0.0 0.2 5648 2768 pts/1 S+ 16:09 0:00 /bin/Bash ./sleep.shadmin@myhome:~$ pgrep sleep.sh24184admin@myhome:~$ kill -9 24184admin@myhome:~$ pgrep sleep.shadmin@myhome:~$ ps aux | grep sleepadmin 24189 0.0 0.0 4732 732 pts/0 S+ 16:09 0:00 grep sleepFirst, I used ps aux and searched in the output for the sleep.sh process, just to show you that it’s there. Next, I used pgrep to find the PID of my running script quickly. I have supplied this PID to the kill -9 command. In effect, sleep.sh has been killed. This can be confirmed on another Terminal, where I was running sleep.sh:
admin@myhome:~$ ./sleep.shKilledHad I simply used kill, the output would be different:
admin@myhome:~$ ./sleep.shTerminatedThere is another way of delivering two of all signals to running programs, but only if currently executing in the shell we’re logged into in the foreground; this means it has the control of the screen and keyboard:
- Pressing the Ctrl + C keys will send
SIGINTto the program.SIGINTtells the program that the user has pressed the key combination and it should stop. It’s still up to the program how the termination should occur. - Pressing the Ctrl + D keys will send
SIGQUIT—it is likeSIGINTbut also produces a so-called core dump, or a file that can be used in a debugging process.
The common way of denoting those combinations in text is ^c and ^d (^ for the Ctrl key), ctrl+c and ctrl+d (ctrl being a shortcut for the Ctrl key), and C-c and C-d (C denoting the Ctrl key, again).
Looking for something?
Section titled “Looking for something?”There are times when you need to look for a directory or a file on the filesystem. Linux has a set of commands that let you perform this operation. Of them all, find is the most powerful. To cover all of its abilities would take a lot more space than we have. You can look for a file or directory of both that have exactly the name you specified, that have part of the name that you specified, that have been modified at a defined point in time, that are owned by a user or a group, and many more scenarios. Additionally, on each file that has been found, an action can be performed, such as rename, compress, or search for a word.
In the following example, we’re looking for a file, signals.h, in the / usr directory:
admin@myhome:/$ find / -name os-releasefind: '/lost+found': Permission deniedfind: '/etc/sudoers.d': Permission denied/etc/os-releasefind: '/etc/ssl/private': Permission denied/usr/lib/os-release[...]First, we call find itself, then we tell it to start looking at the beginning of the filesystem (/), and then we tell it to look for a file named os-release (- name os-release).
You will notice that in the output, which I have cut for brevity, there are errors about files to which find had no proper rights.
If you are unsure about the case of the name, that is, whether it contains lowercase or uppercase letters (remember that Linux is case -sensitive and OS-Release is not the same file as os-release), you can use the -iname option instead.
If you are sure that what you are looking for is a file, then you can use the -type f option:
admin@myhome:/$ find / -type f -name os-releaseFor a directory option, use - type d.
To look for files that match a pattern, say filenames that end with .sh, you’d use a pattern:
admin@myhome:/$ find / -type f -name "*.sh"The asterisk means any number of any characters. We enclosed it in the quotes to avoid problems with the shell interpreting the asterisk before find got a chance. We will explain all the special signs (called globs) and regular expressions in the next chapter, Intermediate Linux.
To delete all found files, you can use the - delete option:
admin@myhome:~$ find . -type f -name test -deleteTo perform an action on the found file, you can use the - exec option:
admin@myhome:/$ find / -type f -name os-release -exec grep -i debian {} \;PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"NAME="Debian GNU/Linux"ID=debianHOME_URL="https://www.debian.org/"SUPPORT_URL="https://www.debian.org/support"BUG_REPORT_URL="https://bugs.debian.org/"In the preceding example, we have used the command called grep to look for any line that contains the word debian, no matter whether uppercase or lowercase.
This leads us to the grep command.
The grep command is used to look for an occurrence of a pattern inside a file. Upon finding this pattern-matching line, it prints it. The grep command is similar to the find command, except its purpose is to search inside the files, while find only cares for the characteristics of files and directories themselves.
Assume a text file called red_fox.txt with the following content:
admin@myhome:~$ cat red_fox.txtThe red foxjumps overthe lazybrown dog.As a side note, cat is a command that prints the contents of a specified file to the Terminal.
Let’s say we want to find all lines that contain the word the:
admin@myhome:~$ grep -i The red_fox.txtThe red foxthe lazyYou have probably guessed that the -i option means that we don’t care about the case.
But wait. We can search for alternatives. Let’s say we care for lines that contain either fox or dog. You would use the -e option for each word you search for or the -E option with all the words in single quotes and separated by the | character:
admin@myhome:~$ grep -e fox -e dog red_fox.txtThe red foxbrown dog.admin@myhome:~$ grep -E 'fox|dog' red_fox.txtThe red foxbrown dog.By adding the -n option, you’ll get information on which line the match was found in:
admin@myhome:~$ grep -n -E 'fox|dog' red_fox.txt1:The red fox4:brown dog.You can look for lines that start with a given word or have the specified pattern at the end of the line.
You can even grep all files in a directory hierarchy. The syntax is a bit different then: the pattern comes first, and the directory comes at the end. Also, you get the name of the file where the match was found:
admin@myhome:~$ grep -r "fox" ../red_fox.txt:The red foxThe most power for both find and grep comes from a concept called regular expressions (regex or regexp for short), which have a book of their own and can be confusing for new users. We are going to explain them in Chapters 3 and 4. We will, however, be only introducing the most everyday uses of them.
If you are looking for a program and want to know its full path, there is a command for that, and it is called whereis. Here is an example:
admin@myhome:~$ whereis pingping: /usr/bin/ping /usr/share/man/man8/ping.8.gzThe whereis command will not only print the whole path to the binary but also a corresponding man page, if it has one installed.
Let’s be manipulative
Section titled “Let’s be manipulative”There are four basic operations that can be performed on files and directories:
- Create
- Rename or move
- Remove
- Copy
Each of these operations has a special tool:
mkdir: This command has very simple and limited syntax. Basically, you are telling it to create a directory with a given name. If you are creating nested directories, that is, one folder contains another, all the directories in the path must exist. If they don’t, you can create them using the special-poption:
admin@myhome:~$ mkdir testadmin@myhome:~$ ls -ltotal 4drwxr-xr-x 2 admin admin 4096 Aug 24 15:17 testadmin@myhome:~$ mkdir something/newmkdir: cannot create directory 'something/new': No such file or directoryadmin@myhome:~$ mkdir -p something/newadmin@myhome:~$ ls -ltotal 8drwxr-xr-x 3 admin admin 4096 Aug 24 15:18 somethingdrwxr-xr-x 2 admin admin 4096 Aug 24 15:17 testIn the preceding example, you can see that I create a directory test directly in my home folder. Next, I try to create a folder, new, inside the something folder. However, the latter doesn’t exist and mkdir tells me so and refuses to create the new directory. I use the special -p option to create a whole path to the new directory.
mv: This is a command that is used to move and rename files and directories. Again, the syntax is pretty simple, although this command offers a little more functionality, such as creating a backup of moved files. To rename a file or directory, we move it from the current name to the new one:
admin@myhome:~$ mv test no-testadmin@myhome:~$ ls -ltotal 8drwxr-xr-x 2 admin admin 4096 Aug 24 15:17 no-testCheck out its man page or help message to find out more.
rm: This command is more interesting, mainly because it offers safety features. With the special-ioption, you can tell it to always ask you before removing the file or directory. Normally,rmbails at directories, as in the following example:
admin@myhome:~$ admin@myhome:~$ ls -l no-test/total 0-rw-r--r-- 1 admin admin 0 Aug 24 15:26 testadmin@myhome:~$ rm no-test/rm: cannot remove 'no-test/': Is a directoryadmin@myhome:~$ rm -d no-test/rm: cannot remove 'no-test/': Directory not emptyadmin@myhome:~$ rm no-test/testadmin@myhome:~$ rm -d no-test/I created a file test inside the no-test directory. rm refuses to remove the folder. I used the -d option, which instructs the command to remove empty directories. However, it still contains a file. Next, I removed the file and then rm -d cleanly deleted the no-test folder. I could have used the -r option, which makes the command remove all directories, even if they are not empty.
cp: This command is used for copying files and directories. Note that, as withrm,cpwill refuse to copy directories unless instructed with the-roption.cparguably is the most complex and feature-rich command of all, including the ability to back up files, create links (shortcuts) instead of real copies, and more. Check out itsmanpage. In the following example, I copy asomethingdirectory to anewdirectory. Obviously, I have to use the-roption. Next, I create an empty file calledfileand copy it tonewfile. For those, I don’t require any options:
admin@myhome:~$ ls -ltotal 4drwxr-xr-x 3 admin admin 4096 Aug 24 15:18 somethingadmin@myhome:~$ cp something/ newcp: -r not specified; omitting directory 'something/'admin@myhome:~$ cp -r something newadmin@myhome:~$ ls -ltotal 8drwxr-xr-x 3 admin admin 4096 Aug 24 15:33 newdrwxr-xr-x 3 admin admin 4096 Aug 24 15:18 somethingadmin@myhome:~$ touch fileadmin@myhome:~$ cp file newfileadmin@myhome:~$ ls -ltotal 8-rw-r--r-- 1 admin admin 0 Aug 24 15:33 filedrwxr-xr-x 3 admin admin 4096 Aug 24 15:33 new-rw-r--r-- 1 admin admin 0 Aug 24 15:34 newfiledrwxr-xr-x 3 admin admin 4096 Aug 24 15:18 somethingYou should now understand and be able to use basic command-line commands in Linux or a similar system, such as create, copy, and delete files; you can also find content inside text files or find files or directories by name. You also have an understanding of processes in the system you work on. In the next chapter, we will deepen this knowledge.
Summary
Section titled “Summary”We have presented but a fraction of the hundreds of commands that Linux admins may use in their work. As mentioned at the beginning of this chapter, the complete reference is beyond the scope of this book. What we have learned, however, is enough to do basic system use and it builds the base for our next chapter: the more advanced Linux administration topics.
Exercises
Section titled “Exercises”- Find out how to apply
chownrecursively—it means that ourchowncall should step inside a directory and apply the change to all the items within. - Find out what the
watchcommand does. Use it with apscommand. - Find out how to remove a directory.
- For all the commands you have learned here, read their
–helpoutput. Open amanpage and look through it, especially the examples section.
Resources
Section titled “Resources”- You can read more about SELinux here:
- This is a very good publication on Linux systems administration: