Most Linux commands follow the same structure. When you type ls -l /etc
in a terminal, you use three elements: a command, an option and an
argument. Understanding that structure gives you a way of reading almost every
command you will meet, with no need to learn them by heart.
What you will learn
- Break down any command line into command, options and arguments
- Tell apart short options (
-l) and long options (--long) - Read an exit code to know whether a command succeeded or failed
- Interpret the most common error messages
- Combine several options and arguments in the same command
- Write a command's output to a file with
>
The basic structure
A command line is not free-form text: it follows a conventional order. The shell (the program that interprets what you type) merely splits it into words; it is the command itself that recognises its options. Here is the most common pattern. The square brackets mark the optional elements:
command [options] [arguments]This order is a convention, not a shell rule. GNU tools such as ls often
accept an option placed after the argument: ls /var/log -l gives the same
result as ls -l /var/log. A few commands break the pattern: find puts
expressions after its paths, and dd expects name=value pairs. So take the
order options then arguments as the usual form, and the safest one to write.
| Element | Role | Example |
|---|---|---|
| Command | The program to run | ls, cat, mkdir |
| Options | Change how the command behaves | -l, --all, -v |
| Arguments | What the command acts on | /etc, file.txt |
Take a concrete example:
ls -la /var/logls: the command (list the contents of a directory)-la: two combined options,-l(long format) and-a(include hidden files)/var/log: the argument (the directory to list)
Short options and long options
Most commands offer two formats for their options:
| Format | Syntax | Example | When to use it |
|---|---|---|---|
| Short | - plus a letter | ls -l | Day to day, quick to type |
| Long | -- plus a word | ls --all (same as ls -a) | In scripts (files of saved commands), more readable |
Combining short options
Short options combine behind a single dash:
# These two lines do the same thing:ls -l -a -hls -lahOptions that take a value
Some options expect a value:
# Short option with a valuehead -n 5 /etc/passwd # shows the first 5 lines
# Long option with a valuehead --lines=5 /etc/passwd # same thingBe careful, though: there is no universal standard for options. Each command
defines its own, and the same sign changes meaning from one program to another:
-r means "recursive" for cp, but "reverse", that is reverse sort order,
for sort. Facing an unknown command, a reliable reflex is --help, detailed in
Getting help on Linux.
Arguments: what the command acts on
The argument gives the target of the command. Depending on the command, it can be:
- a file:
cat /etc/hostname - a directory:
ls /var/log - some text:
echo "Hello" - a name:
mkdir projects - no target:
lsalone lists the current directory
Several arguments are possible:
cp file1.txt file2.txt /tmp/# ^^^^^^^^^ ^^^^^^^^^ ^^^^^# argument 1 argument 2 argument 3 (destination)Exit codes: success or failure
After every command, the shell keeps its exit code in the $? variable, a
name that holds a value in memory. This code is a number that tells whether the
command succeeded or failed.
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Often a misuse (invalid option, missing argument) |
| 126 | Permission denied (the file exists but is not executable) |
| 127 | Command not found |
To see the exit code of the last command:
ls /etcecho $?# 0: everything went fine
ls /nonexistent-directoryecho $?# 2: error, the directory does not existThe codes in the table are shell conventions: each program may define its own.
ls, for example, returns 2 for an argument that cannot be found (ls /nonexistent-directory) and 1 for a minor problem, such as an unreadable
subdirectory met during ls -lR: the list is displayed, with an extra
Permission denied message. Only 0 always means success.
That code explains a puzzling behaviour at first: many commands succeed
silently. When one of them seems to do nothing, check echo $?: a 0
means it did its job with nothing to say. On Linux, no news is good news.
Reading an error message
Error messages follow a predictable format, read from left to right:
command: target: errorThe first three messages below are already detailed in Open a terminal and understand the prompt. The last two are new:
| Message | Meaning | What to do |
|---|---|---|
command not found | The command does not exist or is not installed | Check the name, install the package |
No such file or directory | The path is wrong or the file does not exist | Check the path with ls |
Permission denied | You do not have the rights | Retry with sudo if legitimate |
Is a directory | You are treating a directory as a file | Check the target: did you mean a file? If you really want to act on a directory, read the command's help (man, --help). Beware, rm -r deletes the whole tree with no way back |
File exists | The file already exists | Pick another name or overwrite on purpose |
A concrete example:
$ cta /etc/hostnamebash: cta: command not foundThe shell tells you that cta does not exist. You made a typo: the command is
cat.
$ cat /etc/hostnamcat: /etc/hostnam: No such file or directoryThe file /etc/hostnam does not exist. An e is missing: it is
/etc/hostname.
The -- separator: end of options
Sometimes an argument looks like an option. For example, deleting a file named -f:
# rm reads -f as the "force" option, the file is NOT deletedrm -f
# Correct: -- marks the end of the optionsrm -- -fThe double dash -- tells the command: "everything that follows is an argument,
not an option".
A perfectly silent failure
This trap is worse than an error message, because rm -f does not
complain. It reads -f as the force option, has
no file left to process, and exits with code 0. The file -f is still
there, and nothing told you so: you believe you deleted it and you move on.
touch ./-frm -fecho $? # 0ls ./-f # the file still existsThe check itself falls into the trap if you are not careful: ls -f would be
read as an option of ls, which would list the whole directory instead of
targeting the file. Hence the ./ prefix.
With another name, rm is friendlier. When a file with that name exists in the
directory, it even suggests the fix:
touch ./-xrm -xrm: invalid option -- 'x'Try 'rm ./-x' to remove the file '-x'.Try 'rm --help' for more information.Two workarounds, both valid: the -- shown above, or the ./ prefix, which
turns the name into a path and removes any ambiguity.
Visual summary
The diagram below takes the three elements of a command, here with two options, in their usual order.
ls -l -a /var/log ── ── ── ──────── │ │ │ │ │ │ │ └─ argument: the target directory │ │ └─ option: include hidden files │ └─ option: long format └─ command: list the contentsPut it into practice
Breaking a command down becomes a reflex once you have used a few of them. The lab sets up a separate working folder on your workstation, with a five-line source.txt file. The commands run on your own machine: from that file, you produce an exact copy (cp), a gzip archive (tar) and a numbered version (cat), looking up the right options in each command's help. The check examines the files you produce, not what you typed: a file written by hand fails, and source.txt must stay intact.
To write the numbered version to a file, one notion remains: redirection. A command usually prints its result on the screen. If you add > file after the command, the result is written to that file instead:
date > time.txtcat time.txtThe first line prints nothing, because the date went into time.txt; cat then displays it. If time.txt already exists, > replaces its content without asking, so never aim it at a file you want to keep, source.txt included.
Key points
- Most commands follow the pattern
command [options] [arguments]: it is the command, not the shell, that recognises its options. - Short options (
-l) can be combined (-lah); long ones (--long) read better in scripts. - An exit code of
0means success; any other number signals an error or a case specific to the program. echo $?shows the exit code of the last command.- The meaning of an option varies from one program to another: facing an unknown command, try
--help. - Error messages give the command, the target and the error, in that order: read them from left to right.
- The
--separator lets you pass arguments that look like options. command > filewrites the output into the file instead of the screen, and replaces the file's content if it already exists.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Getting help on Linux
A new full quiz with random questions
Work again only on the questions you missed