Skip to content
ImagineWorld

How the Command Line Works

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-01-how-the-command-line-works
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num1
chapter_titleHow the Command Line Works
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Before we dive into practical Linux commands, you need to have a basic understanding of how the command line works. This chapter will give you that understanding.

For new developers, we’ll explore the initial skills that you need to get started on the Linux command line. For those with a little more experience, there are still some nuances to discover, such as the difference between “shell” and “command line.” It pays to know the difference!

In this chapter, we will cover the following topics:

  • The basic idea of a command-line interface, or CLI
  • The form that commands take
  • How command arguments work and how they look when you’re typing commands and when you’re looking up documentation
  • An introduction to “the shell,” and how it differs from the “command line”
  • The core rules that the shell uses to look up commands

To begin with, we’ll start off with the basic idea of a command-line interface. We will get ourselves up to speed with how a CLI works and run through a quick example.

What is a command-line interface (CLI)? It’s a text-based environment for interacting with your computer that:

  1. Reads some input from you,
  2. Evaluates (or processes) that input,
  3. Prints some output to the screen in response, and then
  4. Loops back to the beginning to repeat that process.

Let’s look at what happens at each step, on a practical level, with the ls (list) command, which you’ll see in a few pages. For now, it’s enough to know that the ls command lists the contents of a directory.

StepWhat it means
1. Read inputYou type the ls command and press Enter.
2.Evaluate commandThe shell looks up the ls binary, finds it, and tells the machine to execute it.
3. Print outputThe ls command emits some text – the names of all files and directories it found – and the shell prints that output to your terminal window.
4. Loop back to 1 (repeat the process)Once the programs called by the command have exited, repeat the process by accepting more user input.

If you read steps 1-4 again, you’ll notice that the first letter of each step spells “REPL”, which is a common way of referring to this kind of Read-Eval-Print Loop in the languages that invented and refined this workflow, such as Lisp.

To put this into programming terms, you can translate the REPL instructions above into code:

while (true) { // the loop
print(eval(read()))
}

Indeed, you can create a REPL capable of doing basic calculations with just a few lines of code in most programming languages. Here’s a one-liner “shell” program written in Perl:

perl -e 'while (<>){print eval, "\n"}'
1+2
3

Here, we write the code as a parameter, printing the output of the evaluation as long as there is input to read from. At the end, we append a new line and exit.

This program is tiny, but it’s enough to implement an interactive Read-Eval-Print Loop in a command-line environment – a shell. The shells you’ll use in Linux and Unix are significantly more complex than this Perl mini-shell, but the principles are the same.

The point is simple: as a developer, you might already be using REPLs without realizing it, because almost all modern scripting languages come with one. In essence, the Linux (or macOS, or other Unix) command line functions like the “interactive shells” that interpreted languages give you. So even if you’re not familiar with the Lisp REPL, the Perl snippet above should remind you of a very basic Ruby or Python shell.

Now that you understand the basic mechanics of the command-line interfaces you’ll be using in Linux, you’re ready to try out your first commands. To do that, you’ll need to know the correct command-line syntax to use.

All REPLs start by reading some input. On the Linux command line, commands that the shell reads in need to have the correct syntax. Commands take this basic form:

commandname options

In programming terms, you can think of the command name as a function name, and the options as any number of arguments that will be passed to that function. This is important, because there is no single fixed syntax for all the options – each command defines which parameters it will accept. Because of this, the shell can do very little to validate a command’s correctness beyond checking that the command maps to an executable.

Note

The terms “program” and “command” are used interchangeably in this chapter. There’s a very slight difference because some shell builtins are defined in the shell’s code and are therefore not technically separate programs of their own, but you don’t need to worry about it – leave that distinction to the Unix greybeards.

Let’s dive into more complex variations on this “command [options]” syntax, which you’ll see frequently:

command [-flags,] [--example=foobar] [even_more_options ...]

This is the conventional format you’ll see used in help documentation such as the program manual pages (manpages) included in most Linux environments, and it’s fairly simple:

  • command is the program you’re running
  • Items in brackets are optional, and brackets with ellipses ([xyz ...]) tell you that you can pass zero or more arguments here
  • -flags means any valid option (“flag,” in Unix-speak) for that program, e.g. -debug or -foobar

Some programs will also accept short and long versions of a parameter, usually denoted by single- vs. double-hyphenation: so -l and --long might do the same thing. It’s not consistent across commands, though; this kind of behavior requires that the command’s creator implemented short and long arguments that set the same parameter.

Not all commands will implement all these ways of passing configuration when invoking them, but these represent the most common forms you’ll see.

By default, a space denotes the end of an argument, so just like in most programming languages, an argument string that includes spaces must be single- or double-quoted. You’ll read more about this in Chapter 12, Automating Tasks with Shell Scripts.

In just a moment, we’ll follow the process of how the shell interprets a command that you issue using this syntax, but first we want to clearly define the difference between two sometimes-interchangeable terms we’ve been using in this chapter: “command line” and “shell.”

In this book, we refer to a “command-line environment.” We define this as any text-based environment that acts as a kind of REPL, specifically for interacting with the operating system, programming language interpreter, database, etc. A “command-line” environment or interface describes the general idea of how you’re interacting with a system.

But there’s a more specific term which we’ll use here: shell.

A shell is a specific program that implements this command-line environment and lets you give it text commands. Technically, there are lots of different shells which provide the same kind of REPL-based command-line environment, often for wildly different things:

  • Bash is a common shell environment for interacting with Linux and Unix operating systems.
  • Popular databases like Postgres, MySQL, and Redis all provide a shell for developers to interact with and run commands in.
  • Most interpreted languages provide a shell environment to speed up development. In these, valid commands are simply programming language statements. See irb for Ruby, the interactive Python shell, etc.
  • Zsh (the Z shell) is an alternative operating system shell (like Bash), which you might see on some developers’ laptops if they’ve customized their environments.

When we talk about a shell in this book, we’re referring to a Unix shell (generally Bash), which is a command-line interface specifically designed to let you interact with the underlying Linux or Unix operating system.

How does the shell know what to run? (evaluate)

Section titled “How does the shell know what to run? (evaluate)”

After reading in a command, the shell needs to evaluate it, by executing a program, fetching some information, or doing something else that’s actually useful to you.

Note

Such a detailed description of how shells work may seem tedious at first, but we promise that this knowledge will come in handy when you have to troubleshoot an issue with a missing or incorrectly permissioned program.

When you type a command like foobar -option1 test.txt in a shell like Bash and press Enter, a few things happen:

  1. If the command has a path specified, it will be used. This can take various forms:
    • A full path, like /usr/bin/foobar in the command /usr/bin/foobar -option1 test.txt.
      • A relative path, like the current working directory in the command ./foobar-option1 test.txt (the . denotes the current directory, which we’ll cover in the Absolute vs. Relative Filepaths section below; this command essentially says “please execute the “foobar” file that’s in my current directory”).
      • The path may be based on variables and symbols either in:
      • The shell’s environment (env vars) like $HOME/foobar, or - Provided by the shell, like ~/foobar (the ~ character means “this user’s home directory”)
  2. If not, the shell checks to see whether it knows what foobar means:
    • It could be a built-in shell command.
      • It could be an alias, which is a way to set up macros or shortcuts for commands.
  3. If not, the shell generally looks at the $PATH environment variable, which contains a few different locations to check for commands: /bin, /usr/bin, /sbin, etc. Users can add locations to this $PATH list, and various software will modify your $PATH: version managers for scripting languages, Python’s virtual environments, and many other programs make heavy use of this mechanism. The shell tries those places specified in your $PATH, in the order it finds them in the $PATH variable, to see if any of them contain an executable with the name foobar.

If the shell still hasn’t found anything, it’ll return an error like bash: foobar: command not found:.

On the other hand, if at any point the shell indeed finds an executable file named foobar, it executes that file and passes -option1 and test.txt (in that order) as arguments.

At this point, the shell knows what program to use to evaluate the command, and it does so. As the command is evaluated, any output is printed to the user, completing the third step of the REPL process. Now all that’s left to do is to loop back to the beginning and start the process over again, accepting another command as input from the user.

The shell tries its best to guess which program the user wants to run, using the general process we outlined above to resolve ambiguity. However, ambiguity can be a bad thing and lead to misunderstandings or bugs. During troubleshooting, you’ll often want to find out which command is really being run. To accomplish this, you can use the command which <command>, which will print the full path (or the alias or script being run) and will let you know whether that command is a shell builtin. Depending on the system, which might not be available. In these situations, you can use command –v instead. This is the POSIX equivalent, which we’ll learn about next:

bash-3.2$ which ls
/bin/ls
bash-3.2$ command -v ls
/bin/ls

Wikipedia tells us that “the Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems.” Practically speaking, it’s an attempt at defining some common standards between Unix systems, which can otherwise have wildly different sets of basic commands available.

POSIX basically says things like, “every POSIX-compatible OS should have a list command called ls ”; in this case, “every POSIX-compatible OS should have a way to check to see if a matching executable exists for a given command name.”

If your scripts need to be portable across Unix operating systems, restricting yourself to POSIX commands is a good thing to do. However, it’s still not a guarantee – many extremely popular Linux distributions divert from POSIX in numerous ways, most of which you won’t notice until they bite you.

Understanding POSIX is the last brick in the foundation you need before getting started with the practical job of working on the command line. We’ve covered a lot of ground so far:

  • You learned about REPLs and saw how this basic process maps to how all modern shells work
  • We explored the basic command syntax you’ll be using while working with Linux

You saw how your shell decides how to take your command input and “evaluate” it correctly. You learned important terminology that you’ll come across frequently: shell, command-line interface, POSIX, and a few more terms that will pay dividends if you learn them now. Armed with this knowledge, you’re ready to move from theory to practice. In the next section, we’ll talk about the Linux-specific context that you’ll be in while running commands. You’ll learn the absolute basics of the Linux filesystem and how different kinds of paths work. After that, the rest of the chapter is all about running Linux commands!

To work effectively with Linux, you need to know the absolute basics: how the system is structured, how to look and move around on the system, and how to read and edit files. In this section, we’ll cover all of that, and get you comfortable with the very basics of navigating a Linux system.

Throughout the rest of this book, we’ll dive deeper into each of these topics and commands, but we want to make sure you have a minimal, functioning set of skills by the time you get to the end of this chapter.

In graphical user interfaces, directories (called folders in macOS) are represented by icons. Perhaps you’re used to seeing neat little rows of these in your home directory - Desktop, Documents, Videos, and so on. Double-clicking on a directory icon opens a new window with a new view from inside that directory.

When we use the term “filesystem,” we mean exactly this – a collection of directories and files that organizes all data on the system. The underlying concept is exactly the same in a command-line environment, it just looks a bit different.

Instead of seeing lots of windows and icons, everything is represented as text, and the contents of directories are only shown when you ask for them. However, files and directories still work exactly the way that you’re used to.

Keeping the filesystem in your head as you navigate seems difficult at first, but once you get used to it, it’s often a more efficient way of dealing with a computer. After a few days of working this way, most people have no problem holding a detailed view of the filesystem in their heads as they work on a system and verify this view only occasionally.

When beginners work with Linux, they often get caught up on the difference between an absolute path and a relative path. This simple misunderstanding results in frustrating amounts of time wasted staring at errors like this one:

No such file or directory

Because you need to understand paths as a prerequisite for almost every Linux command you run, we’ll cover them first.

An absolute path is the full path to any file on the filesystem, starting from the root directory. You can recognize this because it starts with a /, which references the root directory (the very top, or beginning, of the filesystem, which contains all other files and directories).

Here are some examples of absolute paths:

  • /home/dave/Desktop
  • /var/lib/floobkit/
  • /usr/bin/sudo

These absolute paths are like a full set of driving directions, giving turn-by-turn instructions from a known starting point (your apartment, or in the case of a Unix system, the root directory).

You can immediately recognize an absolute path by the fact that it starts with a “ / ” character. No matter where you are on the filesystem, absolute paths will work, since they are full, unique addresses for file objects.

A relative path is a partial path, and it’s assumed that it starts at the current location instead of at the root directory. You can recognize an absolute path by the fact that it doesn’t start with a / character.

Relative paths are like driving directions that use your current location as the starting point. If you’ve pulled off the road because you’re lost and you need new directions, you want directions that start from your current location, not your home address. Relative paths give you exactly this.

As a result, relative paths are often more convenient to type: if you’re already sitting in your /home/Desktop directory, it’s easier to reference a file as mydocument.txt than as /home/Desktop/mydocument.txt (even though both ways are valid, given your location on the filesystem). The real difference comes when you change directories. When you move up a directory from /home/Desktop to /home, the absolute path will still reference the same file, while the relative path reference won’t (now, typing mydocument.txt would reference /home/mydocument.txt).

Imagine a partial directory structure like this – in our example, we’ll say this is a directory tree listing of /home/dave/Desktop:

Desktop
├── anotherfile
├── documents
│ └── contract.txt
├── somefile.txt
└── stuff
├── nothing
└── important

You’re sitting in this desktop directory; in other words, your current directory (which you can see by running the pwd command) is /home/dave/Desktop.

Here are some example relative paths to files in this desktop directory:

  • anotherfile
  • documents/contract.txt
  • stuff/important

Here are the absolute paths for those same files:

  • /home/dave/Desktop/anotherfile
  • /home/dave/Desktop/documents/contract.txt
  • /home/dave/Desktop/stuff/important

You’ll notice that a relative path is just an absolute path with the path to the current working directory chopped off from the beginning.

Recall our example:

Desktop
├── anotherfile
├── documents
│ └── contract.txt
├── somefile.txt
└── stuff
├── nothing
└── important

Now imagine that you’re in a shell environment and your current working directory is this Desktop directory. You want to list the contract.txt file. How do you reference that file? You’ve got two options:

  1. ls /home/dave/Desktop/documents/contract.txt: This is the absolute path, which works from everywhere.
  2. ls documents/contract.txt: This is a relative path to that file, from your current directory.

On Ubuntu Linux and macOS, you can get to a command-line prompt by opening the “Terminal” application.

Looking around – command-line navigation

Section titled “Looking around – command-line navigation”

As a beginner, the first thing you’ll want to do when you open a shell is to have a look around the system. In this section, we’ll cover the most important commands for navigating around and looking at a Linux environment through a shell window.

That said, let’s dive into some basic Linux commands!

pwd stands for “print working directory,” and when you type it into your terminal, your shell will print out the directory that you’re currently sitting in. The Unix filesystem is often compared to a tree, but for now you can just think of it as a messy desktop with lots of directories inside. If each directory is like a room, pwd lets you see which room your command-line environment is currently visiting.

New shell sessions will usually start in your home directory. If you’re following along on Linux, this will look something like:

~ pwd
/home/dave

If you’re running another flavor of Unix, it may look slightly different. Here’s what you’d see on macOS:

~ pwd
/Users/dave

Regardless of where you are on the filesystem, you can still reference files in all directories (see the Absolute vs. relative file paths section in this chapter), but sometimes moving around makes things easier. We’ll get into the details of filesystem structure in a later chapter.

ls lets you “list” the files in a directory. If you run this command without any arguments, it’ll just list the files and directories in your current directory. If you pass it a path to a directory as an argument, it’ll try to see what’s in that directory and list it out for you:

ls /var/log

List will also take arguments (“flags”). There are many flags, but two commonly useful ones are -l (“long”) and -h (“human-readable”).

ls -l -h
# same thing; you can combine flags
ls -lh
# List a specific directory
ls -lh /usr/local/

A long listing will produce the following output format:

-rw-r--r-- 1 dcohen wheel 0 Jul 5 09:27 foobar.txt

Let’s go through it, column by column:

  • -rw-r--r--: The filetype (the first character) and permissions (three groups of three bits that represent permissions for the owning user, the owning group, and everyone else on the system, respectively).
  • 1: The number of references (hardlinks) to this file.
  • dcohen: The user who owns this file.
  • wheel: The group that owns this file.
  • 0: The amount of disk space used by the file (this one is empty). The -h flag changes this output from the default, number of bytes to something “human-readable,” meaning it’ll show megabytes or gigabytes when appropriate.
  • Jul 5 09:27: File modification time.
  • foobar.txt: The filename.

This shows you output that requires some knowledge that we haven’t covered yet (users, groups, and permissions). That’s okay – we’ll get there in Chapter 7, Users and Groups.

Now that you’ve learned the most basic Linux commands for getting your bearings, let’s talk about navigating to where you want to go in a command line environment.

cd lets you “change directory” to anywhere on the filesystem. Using the rooms metaphor from before, this is the equivalent of teleporting out of your current room and going into a different one.

After you successfully change directory, the pwd command will show your new (updated) location:

bash-3.2$ cd /etc/ssl
bash-3.2$ pwd
/etc/ssl
bash-3.2$ ls
README cert.pem certs misc openssl.cnf private
bash-3.2$ cd certs
bash-3.2$ pwd
/etc/ssl/certs

find allows you to search for files. It is one of the few commands that does not follow the convention of long options (e.g., --name). Instead, its flags are specified with a single dash. Here is an example:

bash-3.2$ find / -type d -name home
/home
...

The above will search / (the whole system) for a directory (-type d) with the name home. Keep in mind that when you are not executing this as the all-powerful root (administrator) user, find will not have permissions to list the contents of many directories, so you will receive output like find: '/root': Permission denied in addition to what is being found.

Another common use case is to execute commands based on the output of find:

bash-3.2$ find . -exec echo {} \;
.
./foobar

This will run the echo command with any found files in place of {}. The resulting output will be much like an invocation of ls.

If, instead of running echo for each found file, we want to pass them as arguments to echo, we can replace + instead of \.

bash-3.2$ find . -exec echo {} +;
. ./foobar

find has many more flags. Which ones, exactly? That depends on the version of find your operating system ships with.

Here are some typical use cases:

  • find -iname foobar: Searches for foobar, but be case-insensitive
  • find -name "foobar*": Searches for files starting with foobar
  • find -name "*foobar": Searches for files ending with foobar

Now that you’ve learned how to find the files you’re looking for, let’s see how to actually read file content on the command line.

less allows you to read a file, one “page” (based on the size of your terminal window) at a time.

less somefile.txt

Running less will open the file and allow you to scroll through it, one line (up/down arrow keys) or one page (spacebar) at a time.

To search inside the file, type /, followed by your search string, and hit Enter. Navigate matches with n (for next) and SHIFT-n (previous).

To quit, type q.

Now that you can find and read files, let’s look at how to change them or create new ones.

touch – create an empty file, or update modification time for an existing one

Section titled “touch – create an empty file, or update modification time for an existing one”

touch creates a file, and therefore requires a file path as your argument. If the path you give it doesn’t exist yet (and presuming you have permissions to do so), an empty file is created at that path.

If a file already exists at the specified path, its access and modification timestamps are updated to the current time. If you only want to update access-time OR modification-time, you can use the -a or -m flags, respectively.

mkdir requires a file path argument and uses it to create (“make”) a directory:

bash-3.2$ mkdir foobar
bash-3.2$ ls
foobar

Optionally, you can feed it additional arguments if you want to create multiple directories:

bash-3.2$ mkdir foo bar baz
bash-3.2$ ls
foo
bar
baz

If you want to create multiple directories nested inside of each other (or if you simply want to ensure that they all exist), you can use the -p flag:

bash-3.2$ mkdir -p /var/log/myapp/error
bash-3.2$ ls /var/log/myapp
error

Even if /var/log/myapp didn’t exist before, running mkdir with the -p flag would have ensured that /var/log/myapp was created, before creating /var/log/myapp/error inside of that. On the other hand, if a directory in the path you’re giving to mkdir -p does already exist, -p won’t hurt it in any way, so it’s safe to run multiple times in a row (“idempotent”). This makes the -p flag standard for scripting use.

rmdir removes empty directories. They have to be empty for this command to work, meaning it’s a relatively safe command to run. Most Linux users end up just using rm instead, because it can do the same thing.

To delete a file, use the rm command:

rm filename

In practice, most people use rm to delete directories as well, because unlike rmdir, it works on directories that are not empty. You’ll need the -r flag to apply the command recursively (to all directories contained by the one you’re deleting), and the -f flag to “force” deletion without a confirmation for each file and directory:

rm –rf /path/to/directory

Note

Be extremely careful when using rm -rf because Linux will let you delete directories that are critical to the operation of your system. For example, rm -rf / is telling rm that you’d like to delete the root directory, which contains everything on the system.

Some Linux distributions and Unix operating systems get around this in creative ways (Ubuntu ships with a version of the rm command that has a --no-preserve-root option as a way of asking “are you sure you want to do this?” and Solaris intentionally used a loose interpretation of what rm should do to avoid deleting the root directory). In practice, these safeguards are easily circumvented. Be careful when using rm, and take care when pasting commands into your shell from the Internet!

mv – move or rename files and directories

Section titled “mv – move or rename files and directories”

mv is a clever one, because it can do two different things using the same syntax. Either it “moves” files from one directory to another, or – alternatively – it can rename a file, keeping it in the same directory.

First, we’ll create a file using touch:

bash-3.2$ touch foobar.txt
bash-3.2$ ls
foobar.txt

Then, we’ll rename the file in place:

bash-3.2$ mv foobar.txt foobarbaz.txt
bash-3.2$ ls
foobarbaz.txt

Note that the command above would overwrite any existing file named foobarbaz.txt, if one existed, so be careful when renaming things.

To move the file to a new directory, we’ll create a new directory and then move the file there:

bash-3.2$ mkdir targetdir
bash-3.2$ mv foobarbaz.txt targetdir/
bash-3.2$ ls targetdir/
foobarbaz.txt

You can combine the operations, too. If you want to move a file to a different directory and rename it at the same time, you can:

bash-3.2$ mv foobarbaz.txt targetdir/renamed.txt
bash-3.2$ ls targetdir/
renamed.txt

All but the most minimal environments tend to come with manual pages (manpages), which are documentation that you can use to learn (or remember) how to use the command-line programs you have available to you.

Use man $COMMANDNAME to get information on a command. For example, man ls will print something like this:

LS(1) General Commands Manual LS(1)
NAME
ls – list directory contents
SYNOPSIS
ls [-@ABCFGHILOPRSTUWabcdefghiklmnopqrstuvwxy1%,] [--color=when] [-D format] [file ...]
DESCRIPTION
For each operand that names a file of a type other than directory, ls displays its name as well as any requested, associated
information. For each operand that names a file of type directory, ls displays the names of files contained within that directory,
as well as any requested, associated information.
If no operands are given, the contents of the current directory are displayed. If more than one operand is given, non-directory
operands are displayed first; directory and non-directory operands are sorted separately and in lexicographical order.
The following options are available:
-@ Display extended attribute keys and sizes in long (-l) output.
-A Include directory entries whose names begin with a dot ('.') except for . and ... Automatically set for the super-user
unless -I is specified.

Since manual pages are automatically opened in a pager application, scrolling, searching, and quitting works using the same shortcuts that you’re used to from the less command.

Keep in mind that man is an old utility which tries to resemble an actual book, with different sections (chapters) that cover different topics. In the example above, the (1) in ls(1) denotes which manual section we’re being shown.

Sometimes a man page with the same name will exist in different sections. To specify a section, add a number before the command name. For example, to receive the same manual as above one might run man 1 ls.

The sections on most Unix-like operating systems are as follows:

  1. General commands, so commands that you typically run on the command line
  2. System calls
  3. Library functions, covering the C standard library
  4. Special files (usually devices, those found in /dev) and drivers
  5. File formats and conventions. This includes configuration files
  6. Games and screensavers
  7. Miscellaneous
  8. System administration commands and daemons

So, if you want to dig deeper into one of the topics we cover in this book, you’ll likely start by looking in manpage sections 1, 5, and 8.

If you are unsure about what the name of the manual page you are looking for is, you can use apropos <keyword> or man -k <keyword> to find it. It will print a list of all manual pages containing the specified keyword.

If you’re in an interactive shell session (i.e., not executing from a script or creating a Dockerfile), you can use shell autocompletion, also known as tab-completion, to construct commands with fewer keystrokes and a lower chance of typos.

To make use of shell autocompletion, start typing a file or directory name and press Tab. The shell will progressively narrow your choices, displaying possible matches below the line you’re typing on. When there’s only one choice left based on what you’ve typed, the shell will autocomplete that command or argument and you can press Enter. Let’s walk through an example.

If you’re sitting in your home directory on a Linux desktop system, the view might look like this:

~ pwd
/home/dave
~ ls
Desktop
Documents
Downloads
Library
Movies
Music
Pictures
Public
code
go

If you want to move to the Documents directory, you’ll use the cd (change directory) command to do that:

~ cd Documents

First, type cd D and hit Tab:

~ cd D
Desktop/ Documents/ Downloads/

You’ll see that the shell has narrowed the ten possible choices down to three. Type another letter and press Tab again. You’ll see that only two items match:

~ cd Do
Documents/ Downloads/

Typing another letter, c, will narrow the choices to just one and another Tab will autocomplete the directory name for you:

~ cd Documents/

As soon as you reach an autocompletion for a directory name, you can execute the command as usual with Enter or continue autocompleting inside of that directory. For example, pressing Tab again here will start the autocompletion process again inside of the Documents directory, leaving the Documents/ prefix and autocompleting valid items to the right of the slash. Your shell’s current working directory won’t change until you have a valid path and press Enter.

This small trick will save you a LOT of typing over the years. Start using it sooner rather than later!

In this chapter, you learned all the basic theory you need to know before working effectively on the command line. You saw practical examples of command-line syntax and learned the basics of how most commands accept arguments.

We also introduced the concept of shells and walked through how executables are looked up once you type a command and press the Enter key. Surprisingly, there are many advanced users who don’t fully understand these two concepts, and it hinders their ability to quickly and efficiently use command-line environments.

Finally, you’ve learned the most important basic commands for getting around a system on the command line. You’ll use these commands almost every single time you work on a Linux system – they represent the absolute basics anyone needs to master before going further. You even learned your first time-saving trick, shell autocompletion.

If you’re following along and trying all of this on a real Linux system (and you should be!), make sure to practice what you’ve learned for a few minutes before moving on to the next chapter. We’ll build on that knowledge throughout the rest of this book.