Linux

Linux guide - The command line

Learn the Linux command line step by step: open a terminal, move through the file system, use absolute and relative paths, and create folders and files.

· 15 min read · level: beginner · on Ubuntu 18.04

Overview

The Linux command line is a text-based way of interacting with your computer. Often called shell, terminal, console, prompt or other names, it can give the impression of being complex and confusing to use. Yet the ability to copy and paste commands from a website, combined with the power and flexibility offered by the command line, means that using it is essential.

This tutorial will teach you a little about the history of the command line, then guide you through some practical exercises to familiarize you with a few basic commands and concepts. We will assume no prior knowledge, but by the end we hope you will feel a little more at ease the next time you are faced with instructions that begin with "Open a terminal".

Originally written by peppertop .

What you will learn

  • A little of the history of the command line
  • How to access the command line from your own computer
  • How to carry out basic file manipulation
  • A few other useful commands
  • How to chain commands together to create more powerful tools
  • The best way to use administrator powers

What you will need

  • A computer running Ubuntu or another version of Linux

Every Linux system includes a command line of one kind or another. This tutorial includes a few steps that are specific to Ubuntu, but most of the content should work whatever your Linux distribution.

Opening a terminal

On an Ubuntu 18.04 desktop environment system, you can find a launcher for the terminal by clicking on the Activities item at the top left of the screen, then typing the first letters of "terminal", "command", "prompt" or "shell". Yes, the developers have configured the launcher with all the most common synonyms, so you should have no trouble finding it.

Illustration 1 — Guide Linux - La ligne de commande

Other versions of Linux, or other versions of Ubuntu, will generally have a terminal launcher located in the same place as your other application launchers. It may be hidden in a submenu, or you may have to search for it in your launcher, but it is likely to be there somewhere.

If you cannot find a launcher, or if you simply want a quicker way of bringing up the terminal, most Linux systems use the same default keyboard shortcut to start it: Ctrl-Alt-T .

Whichever way you launch your terminal, you should end up with a rather plain window with a little strange text at the top, much like the image below. Depending on your Linux system, the colors may not be the same, and the text will probably say something different, but the general layout of a window with a large (almost empty) text area should be similar.

Let us run our first command. Click with the mouse in the window to make sure that this is where your keystrokes go, then type the following command, all in lower case , before pressing the Enter or Return key to run it.

pwd

You should see a directory path printed (probably something like /home/YOUR_USER), and then higher up, another copy of this command.

When you run a command, any output it produces will generally be printed directly in the terminal, and another prompt will appear once it has finished. Some commands can generate a lot of text, others will work silently and output nothing at all. Do not worry if you run a command and another prompt appears immediately, as this generally means that the command succeeded. If you think back to how slow the network connections of our 1970s terminals were, those early programmers decided that if everything was going well, they might as well save a few precious bytes of data transfer by saying nothing at all.

The importance of capitalization Pay very close attention to capitalization when typing on the command line. Typing PWD instead of pwd will produce an error, but sometimes the wrong case can result in a command that appears to run, but does not do what you expected. We will look at case a little more but, for now, just make sure you type all the following lines in exactly the case shown.

A sense of direction

Now let us move on to the command itself. pwd is an abbreviation of " p rint w orking d irectory. All it does is "print" (display) the current working directory of the shell. But what is a working directory ?

An important concept to understand is that the shell has a notion of a default location in which all file operations will take place. This is its working directory. If you try to create new files or directories, display existing files or even delete them, the shell will assume that you are looking for them in the current working directory, unless you take steps to specify otherwise. It is therefore very important to keep track of which directory the shell is in at any given moment; after all, deleting files from the wrong directory could be disastrous. When in doubt, the pwd command will tell you exactly what your current working directory is.

You can change the working directory using the cd command, an abbreviation for

" c hange d irectory". Try typing the following:

cd /
pwd

Note that the directory separator is a forward slash ("/"), not the backslash that you may be used to from Windows or DOS systems

Now your working directory is "/". If you come from a Windows background, you are probably used to each drive having its own letter, with your main hard disk usually being "C:". Unix-like systems do not divide up disks like that. Instead, they have a single unified file system, and individual drives can be attached ("mounted") at whatever location in the file system makes the most sense. The "/" directory, often called the root directory, is the base of this unified file system. From there, everything else branches out to form a tree of directories and subdirectories.

Several roots Be careful: although the "/" directory is sometimes called the root directory, the word "root" has another meaning. root is also the name that has been used for the superuser since the early days of Unix. The superuser, as the name suggests, has more powers than a normal user, so it can easily wreak havoc with a mistyped command. We will look at the superuser account in more detail in section 7. For now, you only need to know that the word "root" has several meanings in the Linux world, so context matters.

From the root directory, the following command will move you into the "home" directory (which is an immediate subdirectory of "/"):

cd home
pwd

To go back up to the parent directory, in this case back to "/", use the special two-dot syntax ( ..) when changing directory (note the space between cd and .., unlike DOS, you cannot type cd .. as a single command):

cd ..
pwd

Typing cd on its own is a quick shortcut for returning to your home directory:

cd
pwd

You can also use .. several times if you have to move up through several levels of parent directories:

cd ../..
pwd

Relative and absolute paths

Most of the examples we have looked at so far use relative paths. That is to say, where you end up depends on your current working directory. Think about trying to cd into the "etc" folder. If you are already in the root directory, this will work fine:

cd /
pwd
cd etc
pwd

But what if you are in your home directory?

cd
pwd
cd etc
pwd

You will see an error saying "No such file or directory" before you can even run the last pwd. Changing directory by specifying the name of the directory or by using .. will have different effects depending on the starting point. The path only has meaning relative to your working directory.

But we have seen two absolute commands. Whatever your current working directory, they will have the same effect. The first, you run cd on its own to go directly to your home directory. The second, you used cd / to switch to the root directory. In fact, any path that begins with a slash is an absolute path. You can think of this as saying "go to the root directory, then follow the route from there". This gives us a much simpler way of switching to the etc directory, no matter where we currently are in the file system:

cd
pwd
cd /etc
pwd

This also gives us another way of returning to your home directory, and even to the folders it contains. Suppose you want to go directly to your "Desktop" folder from anywhere on the disk (note the capital "D"). In the following command, you will have to replace USERNAME with your own user name; the whoami command will remind you of your user name, in case you are not sure:

whoami
cd /home/USERNAME/Desktop
pwd

There is another handy shortcut that works like an absolute path. As you have seen, using "/" at the beginning of your path means "from the root directory". Using the tilde character ("~") at the beginning of your path likewise means "from my home directory".

cd ~
pwd

Have you noticed that the text displayed before your command prompt changes as you move around the file system? On an Ubuntu system, it displays your user name, the network name of your computer and the current working directory. But if you are somewhere in your home directory, it will use "~" as an abbreviation.

Recap -> Let us walk around the file system a little, and keep an eye on the prompt while you do it:

cd
cd /
cd ~
cd /etc
cd /var/log
cd ..
cd

You must be quite bored with simply moving around the file system by now, but a good understanding of absolute and relative paths will be invaluable when we move on to creating new folders and files.

4. Creating folders and files

In this section, we are going to create real files to work with. To avoid accidentally trampling on one of your actual files, we will start by creating a new directory, well away from your home folder, which will serve as a safer environment in which to experiment:

mkdir /tmp/tutorial
cd /tmp/tutorial

Note the use of an absolute path, to make sure that we create the tutorial directory in / tmp . Without the slash at the beginning, the mkdir command would try to find a tmp directory in the current working directory, then try to create a tutorial directory inside it. If it does not find a tmp directory, the command fails.

In case you had not guessed, mkdir is the abbreviation of " m a k e dir ectory". Now that we are safely in our test area (check with pwd if you are not sure), let us create a few subdirectories:

mkdir dir1 dir2 dir3

There is something a little different about this command. So far we have only seen commands that work on their own (cd, pwd) or that have a single item after them (cd /, cd ~). But this time, we have added three things after the mkdir command. These items are called parameters or arguments, and different commands can accept different numbers of arguments. The mkdir command expects at least one argument, whereas the cd command can work with zero or one, but no more. See what happens when you try to pass an incorrect number of parameters to a command:

mkdir
cd /etc ~

Back to our new directories. The command above will have created three new subdirectories in our folder. Let us have a look at them with the ls command ( l i s t):

ls

Note that mkdir created all the folders in one directory. It did not create dir3 inside dir2 inside dir1, or any other nested structure. But sometimes it is handy to be able to do exactly that, and with mkdir there is a way:

mkdir -p dir4/dir5/dir6
ls

This time, you will see that only dir4 has been added to the listing, because dir5 is inside it and dir6 is inside that. Later on we will install a useful tool for viewing the structure, but you already have enough knowledge to confirm it:

cd dir4
ls
cd dir5
ls
cd ../..

The "-p" that we used is called an option or a switch (in this case, it means "create the parent folder as well"). Options are used to change the way a command works, allowing a single command to behave in different ways. Unfortunately, because of the quirks of history and human nature, options can take different forms in different commands. You will often see them as single characters preceded by a hyphen (as in this case), or as longer words preceded by two hyphens. The single-character form allows several options to be combined, although not all commands accept this. And to complicate matters further, some commands do not clearly identify their options at all; whether something is an option or not is dictated solely by the order of the arguments. You do not have to worry about all the possibilities, just know that options exist and that they can take several different forms.

# Ne tapez pas ce qui suit, ceci est juste pour la démonstration
mkdir --parents --verbose dir4/dir5
mkdir -p --verbose dir4/dir5
mkdir -p -v dir4/dir5
mkdir -pv dir4/dir5

Now we know how to create several directories simply by passing them as separate arguments to the mkdir command. But suppose we want to create a directory with a space in the name? Let us try:

mkdir another folder
ls

You probably do not even need to type this one to guess what would happen: two new folders, one called another and the other called folder . If you want to use spaces in directory or file names, you have to escape them. Do not worry, nobody is getting out of prison; escaping is a computing term that refers to the use of special codes to tell the computer to treat particular characters differently from normal. Enter the following commands to try out different ways of creating folders with spaces in the name:

mkdir "folder 1"
mkdir 'folder 2'
mkdir folder\ 3
mkdir "folder 4" "folder 5"
mkdir -p "folder 6"/"folder 7"
ls

Although the command line can be used to work with files and folders with spaces in their names, the need to escape them with quotation marks or backslashes makes things a little more difficult. You can often tell a person who uses the command line a lot just from their file names: they will tend to stick to letters and numbers and to use underscores ("_") or hyphens ("-") instead of spaces.

Creating files using redirection

Our demonstration folder is starting to look rather full of directories, but somewhat lacking in files. Let us remedy that by redirecting the output of a command so that, instead of being printed on the screen, it ends up in a new file. First, recall what the ls command currently displays:

ls

Suppose we want to capture the output of this command as a text file that we can examine or manipulate further. All we have to do is add the greater-than character (">") at the end of our command line, followed by the name of the file to write to:

ls > output.txt

This time, nothing is printed on the screen, because the output is redirected to our file instead. If you simply run ls on its own, you should see that the file output.txt has been created. We can use the cat command to look at its content:

cat output.txt

All right, so it is not exactly what was displayed on the screen before, but it contains all the same data, and it is in a format that is more useful for further processing. Let us look at another command, echo:

echo "This is a test"

Yes, echo simply prints its arguments back (hence the name). But combine it with redirection and you have a way of easily creating small test files:

echo "This is a test" > test_1.txt
echo "This is a second test" > test_2.txt
echo "This is a third test" > test_3.txt
ls

You should use cat on each of these files to check their content. But cat is more than a simple file viewer - its name comes from "concatenate", which means "to link together". If you pass it more than one file name, each of them will be displayed one after the other as a single block of text:

cat test_1.txt test_2.txt test_3.txt

When you want to pass several file names to a single command, there are useful shortcuts that can save you a lot of typing if the files have similar names. A question mark ("?") can be used to mean "any single character" in the file name. An asterisk ("*") can be used to mean "zero or more characters". These are sometimes called "wildcard" characters. A few examples may help; the following commands all do the same thing:

cat test_1.txt test_2.txt test_3.txt
cat test_?.txt
cat test_*

To be continued..