Linux Command Line Basics Guide
Linux Command Line Basics Guide
1. Overview (https://tutorials.ubuntu.com/tutorial/command-line-for-beginners#0)
The Linux command line is a text interface to your computer. Often referred to as the shell, terminal,
console, prompt or various other names, it can give the appearance of being complex and confusing to
use. Yet the ability to copy and paste commands from a website, combined with the power and flexibility
the command line offers, means that using it may be essential when trying to follow instructions online —
including many on this very website!
This tutorial will teach you a little of the history of the command line, then walk you through some
practical excercises to become familiar with a few basic commands and concepts. We'll assume no prior
knowledge, but by the end we hope you'll feel a bit more comfortable the next time you're faced with
some instructions that begin "Open a terminal..."
3. Opening a terminal
On a Ubuntu 18.04 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 few letters of "terminal", "command", "prompt" or "shell".
Yes, the developers have set up the launcher with all the most common synonyms, so you should have no
problems finding it.
Other versions of Linux, or other flavours of Ubuntu, will usually have a terminal launcher located in the
same place as your other application launchers. It might be hidden away in a submenu or you might have
to search for it from within your launcher, but it's likely to be there somewhere.
If you can't find a launcher, or if you just want a faster way to bring up the terminal, most Linux systems
use the same default keyboard shortcut to start it: Ctrl-Alt-T.
However you launch your terminal, you should end up with a rather dull looking window with an odd bit
of text at the top, much like the image below. Depending on your Linux system the colours may not be
the same, and the text will likely say something different, but the general layout of a window with a large
(mostly empty) text area should be similar.
Let's run our first command. Cick the mouse into the window to make sure that's where your keystrokes
will 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 out (probably something like /home/YOUR_USERNAME), then
another copy of that odd bit of text.
There are a couple of basics to understand here, before we get into the detail of what the command
actually did. First is that when you type a command it appears on the same line as the odd text. That text
is there to tell you the computer is ready to accept a command — it's the computer's way of prompting
you. In fact it's usually referred to as the prompt, and you might sometimes see instructions that say
"bring up a prompt", "open a command prompt", "at the bash prompt" or similar. They're all just different
ways of asking you to open a terminal to get to a shell.
On the subject of synonyms, another way of looking at the prompt is to say that there's a line in the
terminal into which you type commands. A command line, if you will. Again, if you see mention of
"command line" — including in the title of this very tutorial — it's just another way of talking about a
shell running in a terminal.
The second thing to understand is that when you run a command any output it produces will usually be
printed directly in the terminal, then you'll be shown another prompt once it's finished. Some commands
can output a lot of text, others will operate silently and won't output anything at all. Don't be alarmed if
you run a command and another prompt immediately appears, as that usually means the command
succeeded. If you think back to the slow network connections of our 1970s terminals, those early
programmers decided that if everything went okay they may as well save a few precious bytes of data
transfer by not saying anything at all.
A sense of location
Now to the command itself. pwd is an abbreviation of ‘print working directory'. All it does is print out the
shell's current working directory. But what's a working directory?
One important concept to understand is that the shell has a notion of a default location in which any file
operations will take place. This is its working directory. If you try to create new files or directories, view
existing files, or even delete them, the shell will assume you're looking for them in the current working
directory unless you take steps to specify otherwise. So it's quite important to keep an idea of what
directory the shell is "in" at any given time — after all, deleting files from the wrong directory could be
disastrous. If you're ever in any doubt, the pwd command will tell you exactly what the current working
directory is. You can change the working directory using the cd command — an abbreviation for ‘change
directory'. 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're coming from a Windows background you're probably used to
each drive having its own letter, with your main hard drive typically being "C:". Unix-like systems don't
split up the drives like that. Instead they have a single unified file system, and individual drives can be
attached ("mounted") to whatever location in the file system makes most sense. The "/" directory — often
referred to as the root directory — is the base of that unified file system. From there everything else
branches out to form a tree of directories and subdirectories.
cd ../../etc
pwd
Notice that mkdir created all the folders in one directory. It didn't create dir3 inside dir2 inside dir1, or
any other nested structure. But sometimes it's handy to be able to do exactly that, and mkdir does have a
way:
mkdir -p dir4/dir5/dir6
ls
This time you'll see that only dir4 has been added to the list, because dir5 is inside it, and dir6 is inside
that. Later we'll install a useful tool to visualise the structure, but you've already got 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 directories,
too"). Options are used to modify the way in which a command operates, allowing a single command to
behave in a variety of different ways. Unfortunately, due to quirks of history and human nature, options
can take different forms in different commands. You'll 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
for multiple options to be combined, though not all commands will accept that. And to confuse matters
further, some commands don't clearly identify their options at all — whether or not something is an
option is dictated purely by the order of the arguments! You don't need to worry about all the possibilities,
just know that options exist and they can take several different forms. For example the following all mean
exactly the same thing:
# Don't type these in, they're just here for demonstrative purposes
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 multiple directories just by passing them as separare arguments to the
mkdir command. But suppose we want to create a directory with a space in the name? Let's give it a go:
mkdir another folder
ls
You probably didn't even need to type that one in to guess what would happen: two new folders, one
called another and the other called folder. If you want to work with spaces in directory or file names, you
need to escape them. Don't worry, nobody's breaking out of prison; escaping is a computing term that
refers to using special codes to tell the computer to treat particular characters differently to normal. Enter
the following commands to try out different ways to create 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 quote 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'll tend to stick to letters and
numbers, and use underscores ("_") or hyphens ("-") instead of spaces.
Well that's a little better, but there's still an error. If you run ls you'll see that most of the folders have
gone, but folder_6 is still hanging around. As you may recall, folder_6 still has a folder 7 inside it, and
rmdir will only delete empty folders. Again, it's a small safety net to prevent you from accidentally
deleting a folder full of files when you didn't mean to.
In this case, however, we do mean to. The addition of options to our rm or rmdir commands will let us
perform dangerous actions without the aid of a safety net! In the case of rmdir we can add a -p switch
to tell it to also remove the parent directories. Think of it as the counterpoint to mkdir -p. So if you
were to run rmdir -p dir1/dir2/dir3 it would first delete dir3, then dir2, then finally delete
dir1. It still follows the normal rmdir rules of only deleting empty directories though, so if there was
also a file in dir1, for example, only dir3 and dir2 would get removed.
A more common approach, when you're really, really, really sure you want to delete a whole directory
and anything within it, is to tell rm to work recursively by using the -r switch — in which case it will
happily delete folders as well as files. With that in mind, here's the command to get rid of that pesky
folder_6 and the subdirectory within it:
rm -r folder_6
ls
Remember: although rm -r is quick and convenient, it's also dangerous. It's safest to explicitly delete
files to clear out a directory, then cd .. to the parent before using rmdir to remove it.
Important Warning
Unlike graphical interfaces, rm doesn't move files to a folder called "trash" or similar. Instead it deletes
them totally, utterly and irrevocably. You need to be ultra careful with the parameters you use with rm to
make sure you're only deleting the file(s) you intend to. You should take particular care when using
wildcards, as it's easy to accidentally delete more files than you intended. An errant space character in
your command can change it completely: rm t* means "delete all the files starting with t", whereas rm
t * means "delete the file t as well as any file whose name consists of zero or more characters — which
would be everything in the directory! If you're at all uncertain use the -i (interactive) option to rm,
which will prompt you to confirm the deletion of each file; enter Y to delete it, N to keep it, and press
Ctrl-C to stop the operation entirely.
6. A bit of plumbing
Today's computers and phones have the sort of graphical and audio capabilities that our 70s terminal users
couldn't even begin to imagine. Yet still text prevails as a means to organise and categorise files. Whether
it's the file name itself, GPS coordintates embedded in photos you take on your phone, or the metadata
stored in an audio file, text still plays a vital role in every aspect of computing. It's fortunate for us that
the Linux command line includes some powerful tools for manipulating text content, and ways to join
those tools together to create something more capable still.
Let's start with a simple question. How many lines are there in your combined.txt file? The wc (word
count) command can tell us that, using the -l switch to tell it we only want the line count (it can also do
character counts and, as the name suggests, word counts):
wc -l combined.txt
Similarly, if you wanted to know how many files and folders are in your home directory, and then tidy up
after yourself, you could do this:
ls ~ > file_list.txt
wc -l file_list.txt
rm file_list.txt
That method works, but creating a temporary file to hold the output from ls only to delete it two lines
later seems a little excessive. Fortunately the Unix command line provides a shortcut that avoids you
having to create a temporary file, by taking the output from one command (referred to as standard output
or STDOUT) and feeding it directly in as the input to another command (standard input or STDIN). It's as
though you've connected a pipe between one command's output and the next command's input — so
much so that this process is actually referred to as piping the data from one command to another. Here's
how to pipe the output of our ls command into wc:
ls ~ | wc -l
Notice that there's no temporary file created, and no file name needed. Pipes operate entirely in memory,
and most Unix command line tools will expect to receive input from a pipe if you don't specify a file for
them to work on. Looking at the line above, you can see that it's two commands, ls ~ (list the contents
of the home directory) and wc -l (count the lines), separated by a vertical bar character ("|"). This
process of piping one command into another is so commonly used that the character itself is often referred
to as the pipe character, so if you see that term you now know it just means the vertical bar.
Note that the spaces around the pipe character aren't important — we've used them for clarity, but the
following command works just as well, this time for telling us how many items are in the /etc directory:
ls /etc|wc -l
Phew! That's quite a few files. If we wanted to list them all it would clearly fill up more than a single
screen. As we discovered earlier, when a command produces a lot of output, it's better to use less to
view it, and that advice still applies when using a pipe (remember, press q to quit):
ls /etc | less
Going back to our own files, we know how to get the number of lines in combined.txt, but given that it
was created by concatenating the same files multiple times, I wonder how many unique lines there are?
Unix has a command, uniq, that will only output unique lines in the file. So we need to cat the file out
and pipe it through uniq. But all we want is a line count, so we need to use wc as well. Fortunately the
command line doesn't limit you to a single pipe at a time, so we can continue to chain as many commands
as we need:
cat combined.txt | uniq | wc -l
That line probably resulted in a count that's pretty close to the total number of lines in the file, if not
exactly the same. Surely that can't be right? Lop off the last pipe to see the output of the command for a
better idea of what's happening. If your file is very long, you might want to pipe it through less to make
it easier to inspect:
cat combined.txt | uniq | less
It appears that very few, if any, of our duplicate lines are being removed. To understand why, we need to
look at the documentation for the uniq command. Most command line tools come with a brief (and
sometimes not-so-brief) instruction manual, accessed through the man (manual) command. The output is
automatically piped through your pager, which will typically be less, so you can move back and forth
through the output, then press q when you're finished:
man uniq
Because this type of documentation is accessed via the man command, you'll hear it referred to as a "man
page", as in "check the man page for more details". The format of man pages is often terse — think of
them more as a quick overview of a command than a full tutorial. They're often highly technical, but you
can usually skip most of the content and just look for the details of the option or argument you're using.
The uniq man page is a typical example in that it starts with a brief one-line description of the
command, moves on to a synopsis of how to use it, then has a detailed description of each option or
parameter. But whilst man pages are invaluable, they can also be inpenetrable. They're best used when
you need a reminder of a particular switch or parameter, rather than as a general resource for learning how
to use the command line. Nevertheless, the first line of the DESCRIPTION section for man uniq does
answer the question as to why duplicate lines haven't been removed: it only works on adjacent matching
lines.
The question, then, is how to rearrange the lines in our file so that duplicate entries are on adjacent lines.
If we were to sort the contents of the file alphabetically, that would do the trick. Unix offers a sort
command to do exactly that. A quick check of man sort shows that we can pass a file name directly to
the command, so let's see what it does to our file:
sort combined.txt | less
You should be able to see that the lines have been reordered, and it's now suitable for piping straight into
uniq. We can finally complete our task of counting the unique lines in the file:
sort combined.txt | uniq | wc -l
As you can see, the ability to pipe data from one command to another, building up long chains to
manipulate your data, is a powerful tool — as well as reducing the need for temporary files, and saving
you a lot of typing. For this reason you'll see it used quite often in command lines. A long chain of
commands might look intimidating at first, but remember that you can break even the longest chain down
into individual commands (and look at their man pages) to get a better understanding of what it's doing.
Many manuals
Most Linux command line tools include a man page. Try taking a brief look at the pages for some of the
commands you've already encountered: man ls, man cp, man rmdir and so on. There's even a man
page for the man program itself, which is accessed using man man, of course.
Don't use su
If anyone asks you to use su, be wary. If you're using Ubuntu the root account is disabled by default, so
su with no parameters won't work. But it's still not worth taking the risk, in case the account has been
enabled without you realising. If you are asked to use su with a username then (if you have the
password) you will have access to all the files of that user — and could accidentally delete or modify
them.
When using su your entire terminal session is switched to the other user. Commands that don't need root
access — something as mundane as pwd or ls — would be run under the auspices of the superuser,
increasing the risk of a bug in the program causing major problems. Worse still, if you lose track of which
user you're currently operating as, you might issue a command that is fairly benign when run as a user,
but which could destroy the entire system if run as root.
Better to disable the root account entirely and then, instead of allowing long-lived terminal sessions with
dangerous powers, require the user to specifically request superuser rights on a per-command basis. The
key to this approach is a command called sudo (as in "switch user and do this command").
sudo is used to prefix a command that has to be run with superuser privileges. A configuration file is
used to define which users can use sudo, and which commands they can run. When running a command
like this, the user is prompted for their own password, which is then cached for a period of time
(defaulting to 15 minutes), so if they need to run multiple superuser-level commands they don't keep
getting continually asked to type it in.
On a Ubuntu system the first user created when the system is installed is considered to be the superuser.
When adding a new user there is an option to create them as an administrator, in which case they will also
be able to run superuser commands with sudo. In this screenshot of Ubuntu 18.04 you can see the option
at the top of the dialog:
Assuming you're on a Linux system that uses sudo, and your account is configured as an administrator,
try the following to see what happens when you try to access a file that is considered sensitive (it contains
encrypted passwords):
cat /etc/shadow
sudo cat /etc/shadow
If you enter your password when prompted you should see the contents of the /etc/shadow file. Now
clear the terminal by running the reset command, and run sudo cat /etc/shadow again. This
time the file will be displayed without prompting you for a password, as it's still in the cache.
Going back to the command that actually installed the new program (sudo apt install tree) , it
looks slightly different to those you've see so far. In practice it works like this:
1. The sudo command, when used without any options, will assume that the first parameter is a
command for it to run with superuser privileges. Any other parameters will be passed directly to
the new command. sudo's switches all start with one or two hyphens and must immediately
follow the sudo command, so there can be no confusion about whether the second parameter on
the line is a command or an option.
2. The command in this case is apt. Unlike the other commands we've seen, this isn't working
directly with files. Instead it expects its first parameter to be an instruction to perform
(install), with the rest of the parameters varying based on the instruction.
3. In this case the install command tells apt that the remainder of the command line will consist
of one or more package names to install from the system's software repositories. Usually this will
add new software to the machine, but packages could be any collection of files that need to be
installed to particular locations, such as fonts or desktop images.
You can put sudo in front of any command to run it as a superuser, but there's rarely any need to. Even
system configuration files can often be viewed (with cat or less) as a normal user, and only require
root privileges if you need to edit them.
Beware of sudo su
One trick with sudo is to use it to run the su command. This will give you a root shell even if the root
account is disabled. It can be useful when you need to run a series of commands as the superuser, to
avoid having to prefix them all with sudo, but it opens you up to exactly the same kind of problems that
were described for su above. If you follow any instructions that tell you to run sudo su, be aware that
every command after that will be running as the root user.
In this section you've learnt about the dangers of the root account, and how modern Linux systems like
Ubuntu try to reduce the risk of danger by using sudo. But any use of superuser powers should be
considered carefully. When following instructions you find online you should now be in a better position
to spot those commands that might require greater scrutiny.
8. Hidden files
Before we conclude this tutorial it's worth mentioning hidden files (and folders). These are commonly
used on Linux systems to store settings and configuration data, and are typically hidden simply so that
they don't clutter the view of your own files. There's nothing special about a hidden file or folder, other
than it's name: simply starting a name with a dot (".") is enough to make it disappear.
cd /tmp/tutorial
ls
mv combined.txt .combined.txt
ls
You can still work with the hidden file by making sure you include the dot when you specify its file name:
cat .combined.txt
mkdir .hidden
mv .combined.txt .hidden
less .hidden/.combined.txt
If you run ls you'll see that the .hidden directory is, as you might expect, hidden. You can still list its
contents using ls .hidden, but as it only contains a single file which is, itself, hidden you won't get
much output. But you can use the -a (show all) switch to ls to make it show everything in a directory,
including the hidden files and folders:
ls
ls -a
ls .hidden
ls -a .hidden
Notice that the shortcuts we used earlier, . and .., also appear as though they're real directories. As for
our recently installed tree command, that works in a similar way (except without an appearance by .
and ..):
tree
tree -a
Switch back to your home directory (cd) and try running ls without and then with the -a switch. Pipe
the output through wc -l to give you a clearer idea of how many hidden files and folders have been
right under your nose all this time. These files typically store your personal configuration, and is how
Unix systems have always offered the capability to have system-level settings (usually in /etc) that can
be overridden by individual users (courtesy of hidden files in their home directory).
You shouldn't usually need to deal with hidden files, but occasionally instructions might require you to cd
into .config, or edit some file whose name starts with a dot. At least now you'll understand what's
happening, even when you can't easily see the file in your graphical tools.
Cleaning up
We've reached the end of this tutorial, and you should be back in your home directory now (use pwd to
check, and cd to go there if you're not). It's only polite to leave your computer in the same state that we
found it in, so as a final step, let's remove the experimental area that we were using earlier, then double-
check that it's actually gone:
rm -r /tmp/tutorial
ls /tmp
As a last step, let's close the terminal. You can just close the window, but it's better practice to log out of
the shell. You can either use the logout command, or the Ctrl-D keyboard shortcut. If you plan to use
the terminal a lot, memorising Ctrl-Alt-T to launch the terminal and Ctrl-D to close it will soon make it
feel like a handy assistant that you can call on instantly, and dismiss just as easily.
9. Conclusion
This tutorial has only been a brief introduction to the Linux command line. We've looked at a few
common commands for moving around the file system and manipulating files, but no tutorial could hope
to provide a comprehensive guide to every available command. What's more important is that you've
learnt the key aspects of working with the shell. You've been introduced to some widely used terminology
(and synonyms) that you might come across online, and have gained an insight into some of the key parts
of a typical shell command. You've learnt about absolute and relative paths, arguments, options, man
pages, sudo and root, hidden files and much more.
With these key concepts you should be able to make more sense of any command line instructions you
come across. Even if you don't understand every single command, you should at least have an idea of
where one command stops and the next begins. You should more easily be able to tell what files they're
manipulating, or what other switches and parameters are being used. With reference to the man pages you
might even be able to glean exactly what the command is doing — or at least get a general idea.
There's little we've covered here that is likely to make you abandon your graphical file manager in favour
of a prompt, but file manipulation wasn't really the main goal. If, however, you're intrigued by the ability
to affect files in disparate parts of your hard drive with just a few keypresses, there's still a lot more for
you to learn.
Further reading
There are many online tutorials and commercially published books about the command line, but if you do
want to go deeper into the subject a good starting point might be the following book:
• The Linux Command Line by William Shotts
The reason for recommending this book in particular is that it has been released under a Creative
Commons licence, and is available to download free of charge as a PDF file, making it ideal for the
beginner who isn't sure just how much they want to commit to the command line. It's also available as a
printed volume, should you find yourself caught by the command line bug and wanting a paper reference.