- Learn
- Computer Science & IT
- Information Technology
- Linux Basics
- Linux Command Line
The Linux Command Line
BeginnerLesson 2 of 7 in Linux Basics Course
What you will learn
- Recognize the shell and its prompt, type commands in the correct form with options and arguments, and use the keys that make command-line work faster and safer.
- Recognize the shell, the terminal and the promptTell the shell apart from the terminal window, read what the prompt says about who and where you are, and use the basic keys to run, stop and repeat commands.
- Write commands with options and argumentsBuild a command from its name, options and arguments, combine short options, use long options and option values, and handle spaces and unusual names correctly.
- Recognize the shell, the terminal and the prompt
- Use the manual pages and the quicker help built into commands and the shell to find out what a command does and which options it has, without leaving the terminal.
- Read and search the manual pagesOpen a man page, understand its sections and SYNOPSIS notation, move and search inside it, choose a manual section and find the right page when you do not know the command name.
- Use quick help and other documentationGet a fast option summary with --help, read help for shell built-ins, find extra documentation in /usr/share/doc and info pages, and treat error messages as clues.
- Read and search the manual pages
- Understand how Linux arranges files in one directory tree, move around it with absolute and relative paths, and list and inspect what each directory contains.
- Understand the directory treeDescribe the single tree that starts at the root directory, recognize the main system directories and the home directory, and follow the rules for file names and hidden files.
- Move around with absolute and relative pathsKnow where you are, change directory, and write paths from the root, from the current directory, with .. and with ~, choosing the right kind of path for each task.
- List and inspect directory contentsList files with ls and its common options, read each column of a long listing, and show hidden files, sizes, sort orders and the contents of subdirectories.
- Understand the directory tree
- Manage files and directories from the shell: create them, copy and move or rename them, and delete them safely, knowing exactly what each command does when names already exist.
- Create files and directoriesMake new directories, including nested ones, create empty files or update their timestamps with touch, and remove empty directories.
- Copy, move and renameCopy files and whole directories with cp, move and rename with mv, predict where the result ends up, and avoid overwriting files by accident.
- Delete files and directories safelyRemove files and directory trees with rm, use the options that ask or force, and follow a routine that prevents deleting the wrong things.
- Create files and directories
- Use the shell's wildcard patterns to name many files at once, predict exactly which names a pattern matches, and use patterns safely with commands that copy, move and delete.
- Match file names with *, ? and [ ]Write patterns with *, ? and bracket expressions, including ranges and negation, and predict which existing names they match, taking case and hidden files into account.
- Use wildcards safely with commandsPredict what the shell passes to a command after expansion, preview patterns before using them, stop expansion with quotes, and use braces to generate names.
- Match file names with *, ? and [ ]
- Recall and repeat earlier commands from the history, store values in shell and environment variables, and control how the shell finds programs through PATH.
- Recall and reuse commands from historyBrowse, search and rerun earlier commands, use history expansion with care, and know where Bash keeps the history and what it records.
- Set and use shell and environment variablesCreate, read and remove variables, export them to the environment, use the common environment variables, quote values correctly and make settings last.
- Control how the shell finds commands with PATHExplain how the shell turns a command name into a program, read and extend PATH, run a program that is not in PATH, and check which program a name runs.
- Recall and reuse commands from history
Linux Command Line study guide
1Work at the shell prompt
A terminal session gives you a place to type instructions and see their results. The shell reads each instruction, while the prompt helps you keep track of your user account and location. You will learn the keys for completing names and correcting a line, then build commands from names, options, and arguments. Getting the spaces and quotes right matters: the shell acts on the words it receives, and a small typing change can name a different file.
1.1 Recognize the shell, the terminal and the prompt
A shell reads commands and starts the work they request. A terminal is the window through which you type and see output. Opening another terminal normally starts another shell session. A console provides a directly attached text screen; an SSH login can provide a shell on another computer.
Read the prompt
In the example prompt sam@laptop:~$, sam is the user, laptop is the host, and ~ means the home directory. The final $ commonly marks an ordinary user. Prompt layouts can change, so use commands to confirm details when needed. whoami prints the account name, and pwd prints the current directory.
A # prompt conventionally marks root, the administrator account. Work as an ordinary user and use administrator rights only when a task needs them. A prompt symbol printed before an example command is not part of the command you type.
Run a first session
Type each line separately and press Enter:
whoami
pwd
date
echo Hello
For the example account, the first two results are sam and /home/sam. date shows the current date and time; echo Hello prints Hello. A command's output appears below its input, followed by a fresh prompt. Some successful commands print nothing: mkdir reports creates a directory silently. Inspect the result with ls when you need confirmation.
Bash, the Bourne Again Shell, is widely used on Linux. Other shells include zsh and fish. echo $0 shows how the current shell was invoked; echo $SHELL shows the account's configured login shell. Starting another shell can make those answers differ. A terminal window does not itself determine which shell runs inside it.
Edit and recover
| Key | Action |
|---|---|
| Tab | Complete a command or file name; press twice to see possibilities when ambiguous |
| Up / Down | Browse previously typed commands |
| Ctrl+C | Cancel the current input line or interrupt a running foreground program |
| Ctrl+L | Clear the screen; clear does this too |
| Ctrl+D on an empty line | End the shell, like exit |
Suppose you type ls Doc and press Tab. If Documents is the only matching name, completion fills it in. If several names begin with Doc, Bash needs more characters or a choice. Completion helps with spelling and case: Documents and documents are different names.
A full-screen program may be waiting for its own key instead of showing the shell prompt. Press q to leave man or less. A plain cat command without a file waits for typed input; Ctrl+C returns you to the shell. Ctrl+C is therefore not the usual terminal copy shortcut. Many terminal emulators use Ctrl+Shift+C and Ctrl+Shift+V for copy and paste.
Keyboard layouts also affect how you enter symbols such as ~, [, and {. Some layouts use AltGr, and a dead-key ~ may need Space before it appears. Type commands with their exact case: LS and ls are different command names.
Key Takeaways
- The shell interprets commands; the terminal displays the session.
- A prompt helps identify the account, host, and current directory.
- Use Tab to complete names and Ctrl+C to interrupt or cancel.
- Ctrl+D on an empty line exits the shell;
qexits a manual pager.
1.2 Write commands with options and arguments
A command line is made of words. The first word names what to run, options change its behavior, and arguments supply the objects or values it works on. Spaces separate those words.
Identify the parts
In ls -l /etc, ls is the command, -l requests a long listing, and /etc is the directory argument. The usage form command [options] [arguments] describes this arrangement; you do not type those square brackets.
Short options use one dash and a letter. ls -a -l, ls -al, and ls -la request the same listing. Long options use two dashes, as in ls --all. Keep long options separate; joining words behind one dash does not create a long option. For example, ls -all is read as the short options -a -l -l.
An option can also need a value. In touch -d 2025-01-31 old.txt, the date belongs to -d; old.txt is the file argument. The long form is touch --date=2025-01-31 old.txt. Read the usage description to see whether an option needs a value and how to supply it.
Keep each name together
The shell treats unquoted spaces as word boundaries. These three lines each name one file:
ls "Annual Report.pdf"
ls 'Annual Report.pdf'
ls Annual\ Report.pdf
The quotes or backslash protect the space; they are not part of the file name. Without that protection, ls Annual Report.pdf requests two files. A similar effect appears with echo: echo Hello world receives two words and prints one separating space, while echo "Hello world" preserves all three spaces inside one argument.
Make options unambiguous
Put options before file arguments. GNU commands often accept them later too, but options first makes a line easier to read and works more widely. For commands supporting it, -- ends option processing. rm -- -draft.txt therefore treats -draft.txt as a file name. The path ./-draft.txt also starts with a dot, so rm ./-draft.txt avoids an option-like first character.
Option letters belong to their command. cp -r copies directories recursively, but ls -r reverses sorting; ls -R lists directories recursively. ls -h changes size display and does not request help. A copied en dash, –, is also different from the ordinary - that options require.
Find out what a name runs
A command may be a program file, a shell built-in, or an alias that expands to another command line. cd is built into Bash because it changes that shell's directory. ls is normally a program, often with an alias adding color. type cd and type ls report the active meaning.
If ls-l fails with command not found, Bash searched for that whole name. Insert the missing space: ls -l. If a command complains about an unrecognized option, check the option's spelling and its documentation; changing the file path will not fix an option error.
Key Takeaways
- Spaces separate the command, options, and arguments.
- Quote or escape a space that belongs inside one name.
- Short options may combine; long options use two dashes.
- An option may require a value of its own.
--or a./path handles a file name beginning with a dash.typedistinguishes a built-in, alias, and program file.
2Find help on the command line
Command-line help lets you answer a specific question without memorizing every option. A manual page gives a full reference; a command's quick help gives a shorter reminder. Bash also has a separate help system for commands built into the shell. You will learn how to choose the right source, read the shorthand in a usage line, search a long page, and use an error message to decide what to check next.
2.1 Read and search the manual pages
A manual page is a detailed reference for a named command or system feature. Open one with man ls. The page normally appears in less, a pager that shows one screen at a time and lets you search without leaving the terminal.
Read the page's structure
The NAME heading identifies the command and its purpose. SYNOPSIS gives its calling pattern. DESCRIPTION and OPTIONS explain behavior and switches. EXAMPLES can show actual uses, while FILES and ENVIRONMENT describe related files and variables. SEE ALSO names related pages. Headings vary because some commands need information that others do not.
A usage line such as ls [OPTION]... [FILE]... is compact notation:
- Literal text, often bold, is typed as printed.
- Placeholder text, often italic or underlined, is replaced with your value.
- Square brackets enclose optional parts.
...means the preceding part can repeat.- A vertical bar separates alternatives.
Both option and file groups in this ls form are optional, so ls alone is valid. In mkdir [OPTION]... DIRECTORY..., the directory group has no square brackets: at least one directory name is required. Do not type DIRECTORY merely because it appears in the manual.
Search while reading
Space or Page Down moves forward a screen; b moves back. Arrow keys move by lines. Lowercase g goes to the beginning, and uppercase G goes to the end. Type /human and press Enter to search for "human". Use n for the next result and N for the previous one. Press q to leave the page; h opens the pager's help.
For a practical search, open man ls, search for /human, and read the entry for -h, --human-readable. It works with a listing that shows sizes, such as -l. Quit the manual and run ls -lh. A file of 2048 bytes appears as 2.0K. Using ls -h alone still gives a plain name listing because no size column was requested.
Choose the right manual section
| Section | Subject |
|---|---|
| 1 | User commands |
| 2 | System calls |
| 3 | Library functions |
| 4 | Special device files |
| 5 | File formats |
| 6 | Games |
| 7 | Overviews and conventions |
| 8 | System administration commands |
The reference passwd(5) names section 5's explanation of the password file format. Run man 5 passwd to select it. Plain man passwd normally opens the command page from section 1.
If you know the purpose but not the command, run apropos directory or man -k directory. They search indexed names and short descriptions. If you already know a name and want its one-line purpose, use whatis ls or man -f ls. A new system may have an empty index, so a failed keyword search does not establish that the command is absent.
Some minimal installations omit manuals. A missing man cd page also commonly reflects that cd is a shell built-in. Use help cd for Bash's own description.
Key Takeaways
- Use
man commandfor a reference and/wordto search inside it. - SYNOPSIS square brackets mark optional parts; ellipses mark repetition.
- A section number chooses among pages sharing one name.
apropossearches purposes;whatislooks up a known name.- Use
helpfor Bash built-ins such ascd.
2.2 Use quick help and other documentation
You do not always need a full manual page. A quick option list, a built-in's own help, or an error message may answer the immediate question. Choose a source that describes the command you are actually running.
Match help to the command
type cp normally identifies a program file, so cp --help gives its usage and options. type cd identifies a shell built-in, so help cd describes Bash's version. help alone lists Bash built-ins; it does not provide a help page for the external program ls.
Most GNU commands support --help, but short option meanings differ. For ls, -h means readable sizes, not help. Reading ls --help is the reliable way to check ls options without guessing from another program.
Suppose you want to create reports/2026/q1, but the parent directories do not exist. Work through the question:
apropos directorysuggestsmkdirfor making directories.mkdir --helpshows-p, --parentsand explains creating missing parents.mkdir -p reports/2026/q1creates the whole route.
The help lookup provides the missing behavior, not just the command name. This matters when you already know mkdir but its ordinary form reports that a parent is missing.
Look beyond the option list
GNU Info manuals are longer linked documents. info coreutils opens documentation for the basic file utilities. Inside Info, n goes to the next node, p to the previous node, u up a level, Enter follows a selected link, and q quits. A node is one part of the linked manual.
Installed packages can also provide documentation under /usr/share/doc/. For example, ls /usr/share/doc/bash lists the Bash package's documentation. These directories may contain README files, change logs, license text, and examples. A .gz suffix marks a compressed file; zless can display compressed text.
Read an error as a clue
An error usually names the command, the object, and the reason. In ls: cannot access 'note.txt': No such file or directory, ls ran, but it could not find that path. Check pwd, the spelling and case, and the directory containing the file. Retyping ls in uppercase would create a separate command-name problem.
rmdir: failed to remove 'photos': Directory not empty means the target exists but still has entries. Listing it, including hidden entries, explains why removal failed. An unknown option is different: a message about --bogus directs you to ls --help because the option itself is invalid.
Local help matches the installed program more closely than an arbitrary web example. ls --version identifies the GNU version when you need to compare documentation. Before using an unfamiliar copied command, identify each option in its own help, especially for commands that remove files or run with administrator rights.
Key Takeaways
- Choose
command --helpfor program options andhelp namefor Bash built-ins. infoand/usr/share/doc/can provide longer explanations and examples.- Use the command, path, and reason in an error to decide what to check next.
3Navigate the Linux file system
Files and directories sit in one tree, and each command works from a particular place in that tree. A path tells it where to go or what to inspect. You will trace paths from the root and from your current directory, use shortcuts for home and parent directories, and read listings that show more than names. These skills let you check your location and the objects you are working with before you change anything.
3.1 Understand the directory tree
Linux arranges files and directories in one tree. A file holds data; a directory, called a folder in a graphical file manager, holds named entries for files and other directories. The tree starts at the root directory, /.
Follow the tree
A forward slash separates path components: /home/sam/photos leads from / into home, then sam, then photos. Other disks appear within the same tree, often below /media or /mnt; they do not need drive letters. A backslash is not a Linux path separator. Bash uses it to protect a following character, as in Annual\ Report.pdf.
Important locations have different jobs:
| Location | Main purpose |
|---|---|
/home | Ordinary users' home directories |
/root | The root user's home directory |
/etc | System configuration |
/bin, /usr/bin | Everyday program files |
/sbin, /usr/sbin | System administration programs |
/tmp | Temporary data that may be cleared automatically |
/var | Changing data, including logs under /var/log |
/dev | Device files |
Many current distributions link /bin to /usr/bin and /sbin to /usr/sbin. You may therefore see two directory names leading to the same installed programs. The root directory / and the directory /root still mean different places: one starts the tree, and the other is one account's home.
Recognize your own files
For the example user sam, the home directory is /home/sam, abbreviated by the shell as ~. /home is its parent, not sam's personal directory. Personal documents and settings normally live in the home directory; /tmp is unsuitable for something you need to keep because temporary data may be removed automatically.
Consider this layout:
/home/sam/
.bashrc
Documents/
cv.pdf
letter.txt
photos/
projects/
notes.txt
website/
index.html
style.css
The full route to the style sheet is /home/sam/projects/website/style.css. The file notes.txt is beside website, not inside it. Each directory's entries determine the next possible step down the tree.
Read names exactly
Names are case-sensitive: notes.txt, Notes.txt, and NOTES.TXT can name three files. Names cannot contain / or a null byte. Simple letters, digits, dots, dashes, and underscores keep everyday names easy to type; common Linux file systems limit a single name to 255 bytes.
A suffix such as .txt is part of a name, not proof of its contents. file report examines the data and might identify a PDF even when the name lacks .pdf.
A leading dot makes an entry hidden from ordinary ls output. .bashrc, .profile, and .config commonly hold settings. Hidden means omitted by the default listing, not protected from access; ls -a reveals these names. The special entry . means the directory itself, and .. means its parent. At the root, .. still leads to /.
Key Takeaways
- Linux paths belong to one tree rooted at
/. /home/sam,/home, and/rootare different directories.- File names are case-sensitive; extensions do not determine contents.
- A leading dot hides a name from an ordinary listing, not from authorized access.
.means the current directory and..means its parent.
3.2 Move around with absolute and relative paths
A path tells a command where to find an object. To read a path correctly, first decide where it begins. An absolute path begins at /; a relative path begins at the shell's current working directory.
Establish your starting point
pwd prints your current directory. From /home/sam, the path projects/website reaches /home/sam/projects/website. From /etc, that same relative path would mean /etc/projects/website. The absolute path /home/sam/projects/website identifies the same location from either starting point.
cd changes the current directory. It does not list the destination's contents or open a file. cd projects moves into a child named projects; cd /etc moves to the absolute location /etc. With no argument, cd returns home. cd - returns to the previous working directory and prints that location.
Work a route one part at a time
Start in /home/sam/projects/website and consider cd ../../photos:
- The first
..reaches/home/sam/projects. - The second
..reaches/home/sam. photosgoes down into/home/sam/photos.
The whole command makes one change to the final destination. From the website directory, cd .. stops at projects, while cd ../.. stops at home. The starting directory matters each time: after you have moved, a second relative command starts from your new location.
A leading ./ explicitly names the current directory. ./notes.txt and notes.txt refer to the same local file. ls ../photos lists a nearby directory without moving your shell there; only a command that changes the working directory, such as cd, changes the base for later relative paths.
Use the home shortcut
At the start of an unquoted word, Bash expands ~ to your home directory. cd ~/Documents therefore works from anywhere for sam. ~alex refers to alex's home directory.
Quoting the tilde stops that expansion: cd "~/Documents" asks for a literal ~ directory below the current directory. If the later part contains a space, leave the tilde outside the quotes:
cd ~/"My Files"
You can also write cd "$HOME/My Files"; double quotes preserve the space while allowing the variable's value to expand.
Diagnose a route that fails
cd /projects asks for projects immediately below /, not below your home. cd.. is a single command name; write cd ... A lowercase documents fails when the real name is Documents. Check the start, each component, and its exact case. Tab completion can fill in an existing name and avoid a typing error.
Absolute paths suit instructions that must work from different locations. Relative paths are convenient for nearby work. Both forms also work as file arguments to cp, mv, ls, and other commands; a path's interpretation does not depend on using it with cd.
Key Takeaways
- Use
pwdto establish the base of a relative path. - Absolute paths start with
/; relative paths start at the current directory. - Read each
..as one step to the parent. cd,cd -, andcd ..have different destinations.- Leave
~unquoted when you want home expansion.
3.3 List and inspect directory contents
ls shows the contents of the current directory, or the files and directories you name. A listing can answer more than "What is here?": options reveal hidden entries, details, sizes, ordering, and subdirectories.
Choose what to show
Plain ls and ls -l omit hidden entries. -a includes them along with . and ..; -A includes hidden entries without those two special names. -F adds a slash after directory names. Output colors are another visual aid, but exact colors depend on the system.
ls projects lists what is inside projects. ls -ld projects instead shows a long listing of the directory entry itself. The -d option changes the object being displayed, not the amount of detail.
Read a long listing
Consider this line from ls -l:
-rw-r--r-- 1 sam sam 2048 Mar 3 14:20 notes.txt
Read from left to right:
-marks a regular file;dwould mark a directory andla symbolic link.- The next nine characters describe permissions for the owner, group, and others.
1is the link count.- The two
samfields identify owner and group. 2048is the file size in bytes.- The date and time describe the last content modification.
notes.txtis the name.
ls -lh displays that size as 2.0K. The -h option changes size formatting, while -l supplies the size column. ls -h alone still shows names without sizes.
A directory's own size is space used for its entries; it is not the sum of all data inside. The heading total 12 describes disk blocks for the listed entries, not twelve files. Use the file-name lines to see the entries themselves.
Order the result
| Options | What comes first |
|---|---|
| No sorting option | Names in the locale's sort order |
-t | Most recently modified entries |
-S | Largest entries |
-r with another order | The reverse of that order |
For example, ls -lt puts newest changes first, while ls -ltr puts them last. ls -lhS shows readable sizes with the largest first. Case and punctuation can sort differently with different locale settings, so do not infer a missing file merely from where you expected its name to appear.
Inspect below the first level
ls -R projects lists the contents of projects, then its subdirectories. With notes.txt beside a directory website, the first heading is projects: and its entries include those two names. A later heading, projects/website:, identifies the listing containing index.html and style.css.
Uppercase -R is recursive. Lowercase -r only reverses sorting. Combining -a with a recursive listing also exposes hidden entries, which can make a result much longer. For one directory's metadata, ls -ld is usually the clearer inspection.
Key Takeaways
-ladds details and-hmakes displayed sizes easier to read.-aincludes hidden entries;-Aomits only.and...-dlists a directory itself;-Rlists its subdirectories.-t,-S, and-rcontrol ordering.- A directory size and the
totalline are not counts or totals of all contained files. - A long listing identifies type, permissions, links, owner, group, size, modification time, and name.
4Create, copy, move and delete files and directories
Creating a directory, copying a file, and renaming a file each change the tree in a different way. The result also depends on whether a destination already exists. You will build a small directory structure, predict where copies and moves end up, and distinguish removing an empty directory from removing an entire tree. Reading the command as an action on specific source and destination paths helps prevent accidental overwrites and removals.
4.1 Create files and directories
mkdir creates directories, and touch creates empty files or updates existing timestamps. These are separate actions: a directory provides a place for entries, while an empty file is already a file even though it contains no data.
Create the directory first
mkdir drafts creates one directory below your current location. mkdir drafts final creates two sibling directories. If a requested name already exists, ordinary mkdir reports File exists.
A path's parents normally need to exist. If reports is missing, mkdir reports/2026/q1 cannot reach the requested location. Add -p to create missing parent directories:
mkdir -p reports/2026/q1
This creates each missing level, and accepts levels already present as directories. Repeating the command is useful when preparing a structure whose existing parts should stay in place. It does not turn an existing regular file into a directory.
Add empty files
touch todo.txt creates a zero-byte file if that name is absent. If the file exists, touch keeps its contents and updates its access and modification times. It is not a command for clearing a file. You can name several files, as in touch a.txt b.txt, or choose a timestamp with touch -d 2025-01-31 old.txt.
Files with content normally come from a program that saves data, such as an editor. Creating a file with touch gives it a name and an empty body; it does not add text for you.
Build a small project
Starting in your home directory, run:
mkdir -p website/css website/images
touch website/index.html website/css/style.css
ls -R website
The first line creates website and its two child directories. The second puts index.html inside website and style.css inside website/css. It does not put either file in images. In the recursive listing, website: has css, images, and index.html; website/css: has style.css; website/images: has no ordinary entries.
Notice that the touch command relies on the parent directories created by mkdir. Reversing those two steps would fail if website did not yet exist.
Remove an empty directory
rmdir website/images removes that empty directory. rmdir website/css fails while style.css remains inside it. A hidden entry also makes a directory nonempty, so inspect it with ls -A if the ordinary listing looks blank.
rmdir -p reports/2026/q1 removes q1, then tries 2026, then reports. It stops when a parent is not empty. That option works upward, while mkdir -p builds missing parents downward.
Spaces still separate arguments. mkdir My Project requests two directories; mkdir "My Project" requests one. A simple name such as my-project avoids the space. The names Reports and reports are distinct, so use the same case in the creation command and in later paths.
Key Takeaways
mkdircreates directories;-palso creates missing parents.touchcreates a missing empty file or updates an existing file without erasing it.- Create parent directories before files inside them.
rmdirremoves only empty directories, including the absence of hidden entries.
4.2 Copy, move and rename
A copy leaves a source in place. A move changes its name or location. To predict the result of either action, read the source path, the destination path, and whether the destination already exists.
Predict a copy's destination
cp notes.txt notes-backup.txt creates a second file named notes-backup.txt. If Documents is an existing directory, cp notes.txt Documents/ instead creates Documents/notes.txt. The final slash expresses the intention to copy into a directory.
When there are multiple sources, the last argument must be an existing directory. cp cv.pdf letter.txt backup/ puts both named files in backup. A missing destination directory is not created automatically by this command.
Directories require recursive copying. cp website website-old omits the directory because no recursive option was supplied. cp -r website website-old copies the tree, but the result depends on the destination:
| Before copying | Location of the copied tree |
|---|---|
website-old does not exist | website-old/index.html, and so on |
website-old exists as a directory | website-old/website/index.html, and so on |
An existing destination directory receives the source directory by name. It is not automatically replaced with the source's contents.
Move or rename
mv draft.txt final.txt renames a file. mv final.txt Documents/ moves it into an existing directory. mv website site renames a directory when site is absent, and needs no recursive option.
Within one file system, a move normally changes directory entries without copying all the data. Moving across file systems can require copying and removing data, so a large move need not finish instantly.
If archive does not exist, mv notes.txt archive renames the file to archive. mv notes.txt archive/ instead requires a directory and fails when that directory is absent. Use the slash when a new file name would be the wrong result.
Control replacement and metadata
Plain cp and mv can overwrite an existing destination file without asking. -i asks before replacement; -n skips existing destinations; -v prints actions. Aliases may add options, so use type cp or type mv if the observed behavior differs.
A newly created ordinary copy gets a new modification time. cp -p preserves timestamps and permissions, while cp -a recursively preserves a directory tree's attributes and is useful for backups. Do not assume a plain copy preserves its source's time merely because the contents match.
Trace a complete operation
From /home/sam, first create backup. cp projects/notes.txt backup/ creates backup/notes.txt. Next, mv backup/notes.txt backup/notes-2026.txt changes only the copy's name. Finally, cp -r projects/website backup/ creates backup/website, including its files. The original projects/notes.txt and projects/website remain where they were because neither was a source of a move.
Key Takeaways
cpleaves the source;mvchanges its name or location.- An existing destination directory receives the source by name.
- Multiple sources require a directory as the final argument.
cp -rcopies a tree;mvneeds no recursive option.-iasks before overwriting and-nskips an existing destination.cp -ppreserves timestamps and permissions;cp -apreserves a recursive tree.
4.3 Delete files and directories safely
rm removes files named by its arguments. Unlike a graphical file manager's trash action, it does not put them in a recycle bin. A backup is normally the route to recovery after a removal.
Select the right removal command
rm old.txt removes a file, and rm a.txt b.txt removes several named files. Plain rm old refuses if old is a directory. rmdir old or GNU rm -d old removes a directory only when empty. rm -r old recursively removes its contents and then the directory itself.
The distinction is useful when you expect an empty directory. rmdir failing with Directory not empty gives you a chance to inspect unexpected contents. Recursive removal would remove those contents too.
Control questions deliberately
| Option | Effect |
|---|---|
-i | Ask before each removal |
-I | Ask once before more than three files or a recursive removal |
-f | Do not ask; ignore missing names |
-v | Print removal actions |
For ordinary interactive input, rm may also ask about a write-protected file. -f suppresses that question. It does not turn the action into a recoverable deletion or remove every possible reason a command might fail.
Check the exact targets
Use this routine before a removal that could affect several names:
- Run
pwdto confirm your location. - List the exact names or pattern you intend to remove.
- Inspect the list, including whether any directories are selected.
- Use the same target expression with
rm, adding-iwhen confirmation helps.
Suppose the directory contains draft1.tmp, draft2.tmp, final.txt, and notes.tmp. ls *.tmp shows the three temporary files. rm -i *.tmp asks about those three names; final.txt does not match. Answering n skips a file, while y confirms removal.
Keep path spelling intact
A space is a word boundary even in a dangerous command. Adding a space between ~/ and a child name changes one home-relative path into two separate targets. Check the whole line before Enter. Avoid forceful recursive removal for routine cleanup when a narrower command serves the task. GNU rm protects / itself by default; that protection does not protect every path below / from a mistaken pattern.
A leading dash can be mistaken for an option. rm -- -draft.txt ends option parsing before the file name. rm ./-draft.txt also names it unambiguously. For a space inside a name, use rm "old notes.txt"; the unquoted version names old and notes.txt separately.
An error needs diagnosis, not stronger privileges by default. If a removal fails, check whether the target is a directory, whether its path is correct, and what the actual message says. Repeating a mistyped command with administrator rights enlarges what the mistake can affect.
Key Takeaways
rmremoves directly; it does not send files to a trash folder.- Use
rmdirfor an empty directory andrm -rfor a tree. - Check the working directory and exact targets before removal.
-iasks per target;-fsuppresses questions and ignores missing names.- Spaces, quotes, and leading dashes change how removal arguments are read.
5Select files with wildcards
A wildcard can turn one short pattern into many file names. Bash does that matching before it starts the command, so the same pattern can serve a listing, a copy, or a removal. You will work out exactly which names match, account for case and hidden entries, and see how quoting changes what reaches a program. Brace expansion adds another useful tool: it produces new names even when no files with those names exist.
5.1 Match file names with *, ? and [ ]
A glob is a file-name pattern. Bash replaces an unquoted pattern with matching existing names before it starts the command. You can use the same pattern with ls, cp, mv, or another command that accepts those names.
Match a name one part at a time
| Pattern part | What it matches |
|---|---|
* | Any sequence of characters, including none |
? | Exactly one character |
[12] | One character: 1 or 2 |
[0-9] | One digit in the range |
[!0-9] | One character outside the digit range |
A pattern matches the whole name. report* matches report because the star may match no characters. beach?.jpg matches beach1.jpg, but not beach10.jpg: two digits cannot fit one question mark. beach[12].jpg restricts that one place to 1 or 2.
For a worked selection, let photos contain beach1.jpg, beach2.jpg, beach10.jpg, city1.jpg, city2.png, IMG_01.JPG, notes.txt, and .index. The pattern *.jpg matches the three beach photos and city1.jpg. city* also matches city2.png because it constrains the beginning, not the suffix. [!b]* matches names whose first character is not b, leaving out both the beach names and the hidden .index.
Account for case and leading dots
Matching is case-sensitive by default. *.jpg does not select IMG_01.JPG. The pattern *.[jJ][pP][gG] accepts either case at each suffix position, so it includes both styles.
A leading dot needs an explicit dot at the start of that path component in ordinary Bash matching. * skips .index; .i* selects it. This rule also applies inside a directory: photos/* skips hidden names in photos. The pattern does not acquire hidden files merely because ls -a is the command receiving it; expansion already happened before ls starts.
A wildcard does not cross /. photos/*.jpg selects matches directly inside photos. */notes.txt selects a matching file exactly one directory level below the current directory. It does not search every deeper directory.
Read character sets carefully
[abc] offers one character position, not a choice among whole file names. A leading ! or ^ negates the set. A range such as [a-f] follows locale rules, which can affect ordering and matching. Named classes use another pair of brackets: [[:digit:]], [[:upper:]], and [[:lower:]]. Their character classifications follow the locale; lowercase characters are not restricted to the ASCII letters a through z.
Globs and regular expressions use different rules. In a glob, a dot is a literal dot and * is already a complete "any sequence" instruction. Do not borrow the meaning of . or * from a text-search pattern when predicting file-name matches.
Key Takeaways
- Bash expands globs into matching existing names before a command runs.
*matches zero or more characters;?and a bracket set each match one.- Case and a leading dot affect matching.
- Wildcards match within one path component and do not cross
/. - Character ranges and classes depend on locale.
- Globs and regular expressions interpret symbols differently.
5.2 Use wildcards safely with commands
A program receives the names Bash produces, not the wildcard expression that selected them. That makes previewing useful: you can inspect the selected arguments before a command changes files.
Expand, then run
If notes.txt and todo.txt are the only .txt names, ls *.txt receives those two names. The shell performs the matching; ls is then free to list each argument according to its own rules. Matching directories count as names too, so a pattern is not a guarantee that every target is a regular file.
echo *.tmp prints the expanded words without changing files. ls -d -- *.tmp lists the matching entries themselves, including any directory entries, instead of showing their contents. For uncomplicated file names, these previews make it easy to check the selection before copying, moving, or removing.
In default Bash, a pattern with no match remains unchanged. If no .pdf name exists, echo *.pdf prints *.pdf; ls *.pdf tries to access that literal name and reports that it does not exist. A printed star therefore can be evidence of no match, not a real list of selected files.
Decide who should see the pattern
Quotes stop wildcard expansion. echo '*.txt', echo "*.txt", and echo \*.txt all print the literal pattern. In contrast, echo *.txt asks Bash to select existing matching names. Quoting is appropriate when the program itself should receive special characters, or when a real file has a star in its name.
Keep that choice separate from quoting spaces. A file name selected by glob expansion remains one argument even if the selected name contains a space. But a variable holding a path should normally be double-quoted when used, because its unquoted expansion can split into words.
Check the command's destination
cp *.jpg ~/backup/ copies matching names into an existing backup directory. mv draft* archive/ moves matching names into an existing archive directory. A final slash requires a directory destination, helping expose a missing destination instead of silently renaming a single source.
A broad * includes directories. cp * backup/ copies ordinary files but omits directories without recursive copying. Adding -r includes directories, including backup itself when it is inside the current directory; cp then refuses to copy that directory into itself. Put a backup outside the selected source set or choose a narrower pattern.
Spacing changes selection. *.tmp is one pattern; * .tmp is a broad pattern plus a separate dot-name argument. Preview the actual expression you will use.
Generate new names with braces
Brace expansion writes out words whether or not they exist:
mkdir -p project/{src,docs,tests}
touch file{1..3}.txt
cp notes.txt{,.bak}
The first line creates three named children. The second produces file1.txt, file2.txt, and file3.txt. The last expands to cp notes.txt notes.txt.bak; its first brace choice is empty. Use braces to generate names and globs to select existing ones.
Key Takeaways
- Preview the actual pattern before using a command that changes files.
- No match leaves the pattern literal in default Bash.
- Quotes or a backslash keep wildcard characters literal.
- Globs select directories as well as regular files.
- Brace expansion creates words even when matching files do not exist.
6Reuse commands and work with variables
A shell can remember your commands and hold values that you use again. History saves typing, variables name useful values, and the environment passes selected values to newly started programs. PATH uses an environment variable to tell Bash where to look for program files. You will connect these features with quoting, command lookup, and startup files so you can explain both what works now and what a later terminal session will inherit.
6.1 Recall and reuse commands from history
Bash keeps a history list of commands entered in the shell. You can recall a line, inspect it, change one part, and run the edited version. This is especially useful for a long path or an option combination you used recently.
Recall a line before running it
The Up and Down arrows move through earlier commands. The recalled line becomes editable input; it is not executed until you press Enter. history prints the numbered list, and history 5 limits the output to recent entries.
Ctrl+R searches backward. Type part of a command, such as mkdir, to find the latest matching line. Press Ctrl+R again for an older match. Enter runs the shown command, while Ctrl+G cancels the search. Read the whole result, since the matched fragment may appear in several commands with different paths.
Understand exclamation-mark shortcuts
History expansion rewrites expressions before execution:
| Expression | Reused text |
|---|---|
!! | The preceding command |
!42 | History event 42 |
!ls | The latest command starting with ls |
!$ | The last argument of the preceding command |
For example, immediately after mkdir -p reports/2026, cd !$ expands to cd reports/2026. The shortcut refers to the preceding command, so another command entered between those lines would change what !$ selects. To repeat a numbered command, use its event number; to reuse its last argument, use a word shortcut in the proper context.
Expansion normally prints the expanded command and runs it straight away. The display is not a confirmation prompt. A :p modifier, such as !rm:p, prints the expansion without running it. Arrow recall or Ctrl+R is often easier when you want to inspect and edit a potentially destructive line. You may see sudo !! used to repeat the last command with administrator rights; inspect the intended action before deciding that additional rights are appropriate.
Know what is saved
The active shell holds history in memory. On exit, it normally writes to the file named by HISTFILE, usually ~/.bash_history. Each terminal has its own in-memory list, so two open terminals need not show the same history at that moment.
HISTSIZE limits the number of commands kept in memory. Bash's built-in default is 500, though distributions often change it. HISTFILESIZE limits lines in the saved history file. These settings control different places, so changing one does not mean you changed both limits.
HISTCONTROL=ignorespace omits lines beginning with a space; ignoredups omits a line identical to the preceding one; ignoreboth combines them. These are configuration choices, not reasons to assume an arbitrary terminal leaves a command unrecorded. history -d 42 removes an entry, and history -c clears the current in-memory list.
Passwords placed in command arguments can be stored in history. Let a program request a password through its own prompt instead of putting it in the command line.
Key Takeaways
- Arrow recall and Ctrl+R let you inspect a command before Enter.
!!, numbered events, prefixes, and!$refer to different earlier text.- History expansion normally runs immediately;
:pprints without running. - The active history list and the saved history file have separate limits.
- Keep passwords out of command arguments.
6.2 Set and use shell and environment variables
A variable gives a value a name. Bash can substitute that value into later command lines. An environment variable is also passed to programs started from that shell, letting those programs read settings such as language or home location.
Assign and read a value
Write an assignment without spaces around =:
city=Lisbon
echo "$city"
echo "${city}_trip"
The first line stores Lisbon; the next lines print Lisbon and Lisbon_trip. Braces mark where the variable name ends. Without them, $city_trip means a different variable named city_trip.
city = Lisbon is not an assignment: Bash tries to run a command named city with two arguments. Names are case-sensitive and may contain letters, digits, and underscores, but cannot start with a digit. Reading an unset variable gives an empty value in ordinary Bash use. unset city removes the value.
Choose quotes for the job
| Input | What Bash does |
|---|---|
echo "$HOME" | Expands HOME and keeps the result together |
echo '$HOME' | Passes the literal text $HOME |
echo \$HOME | Protects the dollar sign, also printing $HOME |
After greeting="Good morning", echo "$greeting, $USER" prints the greeting and account name as one argument. Double-quote a variable used as a path when its value may contain spaces. Single quotes protect everything inside them, including the dollar sign, so they cannot serve the same purpose as double quotes when you want a variable expanded.
Pass settings to child programs
A plain assignment creates a shell variable. export city marks it for the environment; export city=Lisbon combines both actions. Compare:
city=Lisbon
bash -c 'echo $city'
export city
bash -c 'echo $city'
If city was not previously exported, the first child shell prints an empty line. After the export, a newly started child receives Lisbon. Export passes a copy at launch; it does not update programs that are already running.
env and printenv list environment entries, while printenv HOME shows one. set lists shell variables and functions too. Common settings include HOME for home, USER for the user, PWD for the working directory, SHELL for the login shell, LANG for language and regional formats, and PATH for program lookup. Lowercase names for your own values avoid collisions with these conventional uppercase names.
Control lifetime and startup
An assignment before one command supplies a setting just to that command: TZ=Asia/Tokyo date prints Tokyo time without replacing the shell's time-zone setting. LC_ALL=C ls --help requests untranslated messages.
An unsaved prompt setting belongs to that shell; opening a separate terminal does not make it persistent. Put a repeated setting such as export EDITOR=nano in ~/.bashrc for interactive non-login Bash shells. Login shells read profile files, which often load that file. A new non-login shell reads the saved setting; source ~/.bashrc applies the file in the current shell.
Key Takeaways
- Assignments have no spaces around
=;$namereads the value. - Double quotes allow expansion while preserving spaces; single quotes keep text literal.
exportpasses a variable to subsequently started child programs.envshows the environment;setalso includes shell variables and functions.- A leading assignment can affect just one command.
- Startup files make saved settings available in later shells.
6.3 Control how the shell finds commands with PATH
When you enter a command name, Bash needs to decide what that name means. It can be an alias, function, built-in, or program file. PATH controls the program-file search for a name that has no slash.
Read the search list
PATH holds directory names separated by colons, for example /usr/local/bin:/usr/bin:/bin. echo "$PATH" prints the list. Bash considers shell-defined meanings first; for an external program name, it searches the listed directories from left to right and uses the first executable match.
The directory names matter, not the fact that a program is installed somewhere. A file outside the search list is not found by a bare name. Everyday programs are commonly under /usr/bin or /bin; administration programs use /usr/sbin or /sbin; local installations often use /usr/local/bin. Personal programs can live under ~/bin or ~/.local/bin.
If two PATH directories contain a program with the same name, the earlier directory wins for a fresh lookup.
Inspect the active command
type cd identifies a shell built-in. type ls may identify /usr/bin/ls or report a color alias. type -a echo lists the built-in and external matches. which ls normally reports a program path from PATH, but it can miss shell features that type knows about. Use type when you want to understand what Bash will actually do.
Run an explicit path
The usual PATH omits the current directory. An executable file named backup beside your prompt therefore needs ./backup unless its directory is in PATH. A command name containing / names a location directly:
./backup
/home/sam/bin/backup
Both forms bypass the PATH search. The first is relative to your working directory; the second starts from /. The file must still be executable. Merely being able to list or read it does not make it runnable.
Extend without replacing
To add a personal directory at the end, retain the existing value:
export PATH="$PATH:$HOME/bin"
The colon separates the old list from the added directory. With an executable backup in /home/sam/bin, a later backup command can now find it. Appending keeps any earlier matching program ahead of your new directory. Placing the new directory first would change which duplicate name wins.
PATH=$HOME/bin instead discards every existing directory in the value. External commands such as ls may stop working by bare name. Opening a fresh terminal with the normal startup configuration restores its normal PATH; for the current shell, export PATH=/usr/local/bin:/usr/bin:/bin supplies a basic repair list. Built-ins can still work because they are not found through PATH.
To retain an intended addition for new interactive non-login shells, save its export line in ~/.bashrc.
Key Takeaways
- PATH is a colon-separated list searched from left to right for external commands.
typealso reports aliases, functions, and built-ins.- A command containing
/names a path directly and bypasses PATH. - Keep
$PATHwhen extending the list. - Search order decides which duplicate external program name wins.
Linux Command Line examples
1Build and read a command
11 steps
- 1IntroductionRead a terminal session
A terminal shows a conversation: you type a command, the shell interprets it, and any result appears below. The prompt marks the point where another line can begin.
We will read that prompt, use a few keys, and build a command whose spaces and options mean exactly what we intend. The goal is to understand the line before pressing Enter.
- 2ExplanationIdentify the shell and the window
The shell is the interpreter. The terminal is the window displaying its input and output. Bash is one commonly used Linux shell; a different terminal window can still run Bash.
In
sam@laptop:~$, the prompt identifies sam on laptop, working at home. The final dollar sign conventionally marks an ordinary user. Do not type that prompt symbol when entering an example command. - 3ExampleAsk who and where
Enter
whoamiand read the result: for our example account, it issam. Then enterpwd; from home it prints/home/sam. Each command is a separate input line.The output is information returned by the command, not text you need to type again. A new prompt means the shell is ready. A successful command can also be silent, so output length is not a measure of success.
- 4TipComplete, cancel, or leave
Start a directory name and press Tab to complete it. When more than one name fits, add more characters or press Tab twice to see possibilities. Completion follows the actual spelling and case of existing names.
Ctrl+C cancels input or interrupts a foreground program. Ctrl+D on an empty line ends the shell. In a manual pager,
qquits the page; the same keystroke has different meaning from a command typed at the shell prompt. - 5ChallengeChoose the recovery key
You have typed
ls-l, noticed the missing space, and want to discard the whole input line before it runs. What key returns you to a fresh input line?---reveal---
Press Ctrl+C. It cancels the pending input without running it. Ctrl+L clears the screen instead; it is not the same as discarding what you typed. You could also edit the line to
ls -l, but the requested action here is cancellation. - 6ExplanationGive each word a job
Read
ls -l /etcas three words with three jobs.lsidentifies the command,-lchanges its behavior, and/etcnames what to list. The separating spaces let Bash pass those parts separately.Short options have one dash; long options have two.
ls -lacombines-land-a, whilels --allis one long option. Some options also need values, which their help text identifies. - 7ExampleKeep a spaced name together
Suppose one file is named "Annual Report.pdf". Typing
ls Annual Report.pdfsupplies two file arguments because the unquoted space separates words.Write
ls "Annual Report.pdf"to keep the name together. Single quotes also work for this literal name, or you can escape its space asAnnual\ Report.pdf. The protecting characters guide the shell; they do not become characters in the file name. - 8Key InsightOptions belong to their command
A familiar letter can have different meanings in different programs.
cp -rcopies directories recursively, butls -ronly reverses ordering. The recursive listing option is uppercase-R.Likewise,
ls -hformats sizes; it does not ask for help. Read the command and option as a pair. Guessing from an option used with another command can produce a valid command that does the wrong thing. - 9ChallengeBuild one clear listing
A file is named "Course Plan.txt". How can you request its long listing without asking for two separate files?
---reveal---
Use
ls -l "Course Plan.txt". The first space separates the command from the option, and the next separates the option from the quoted argument. The embedded space stays inside one name.ls-lwould instead be a different command name, and unquotedCourse Plan.txtwould be two target arguments. - 10ChallengeHandle two kinds of special text
The file you need to list is "-old notes.txt". You want details and must handle both the initial dash and the internal space. Write a GNU
lscommand for it.---reveal---
Use
ls -l -- "-old notes.txt". The quotes keep the name together, while--tellslsto stop parsing options. Quoting by itself does not remove the leading dash, so it solves the space problem but not the option problem.ls -l "./-old notes.txt"also works. - 11RecapRead the line before Enter
Recognize the prompt, then read the entered line as a command with separate options and arguments. Protect spaces inside names, check option meanings for the command in use, and use completion to reduce typing errors.
When input goes wrong, cancel or edit it before running; when a program takes over the screen, use its own exit or interrupt action.
2Find the command behavior you need
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFind an answer in help
- 2ExplanationOpen the manual for the command
- 3ExampleInterpret optional and repeated parts
- 4TipSearch and return to the prompt
- 5ChallengeSelect the page you need
- 6ConnectionUse the command kind to choose help
- 7ExampleRead the reason for a failure
- 8ChallengeChoose a built-in reference
- 9ChallengeGo from purpose to a working command
- 10RecapMatch the question to the reference
3Navigate and inspect a directory tree
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrace a route through the tree
- 2ExplanationStart from the root
- 3ExampleRead a small layout
- 4ChallengeRecognize a hidden child
- 5ExplanationAnchor the route
- 6ExampleFollow two parents
- 7TipUse home and previous-location shortcuts
- 8ChallengeFind a sibling of the parent
- 9ExplanationAdd the details you need
- 10ExampleSeparate size from ordering
- 11ChallengeChoose the listing for the question
- 12ChallengeTrack a change and an inspection
- 13RecapKeep location and view separate
4Build, copy, rename, and clean up
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPredict the final layout
- 2ExampleCreate the parents
- 3ExampleAdd files to the structure
- 4ChallengeCheck what must exist first
- 5ExplanationCopy one file into a directory
- 6ExampleCopy the tree
- 7ExampleRename within the copy
- 8TipRequire a directory when you mean one
- 9ChallengeLocate a copied child
- 10ExplanationRemove an empty child
- 11TipCheck the target before removal
- 12ChallengeChoose an empty-only action
- 13ChallengeTrace the whole cleanup
- 14RecapRead actions as changes to paths
5Work out a pattern before using it
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPredict a wildcard selection
- 2ExplanationGive each symbol its width
- 3ExampleConstrain one position
- 4Key InsightCase and dots stay significant
- 5ChallengeSelect exact matches
- 6ExplanationLet the shell expand first
- 7ExampleRead a literal pattern
- 8ChallengeDecide what reaches the program
- 9TipKeep the destination outside the selection
- 10ExampleGenerate names before files exist
- 11ChallengeGenerate, move, then select
- 12RecapSeparate selection from generation
6Reuse commands and follow inherited settings
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionReuse a line and a value
- 2ExplanationRecall with a chance to edit
- 3ExampleUnderstand what the shortcut reuses
- 4ChallengeKeep the preceding command straight
- 5ExplanationAssign a value without splitting it
- 6ExampleChoose what the quotes allow
- 7ExampleShare a copy with a child
- 8ChallengePredict inheritance and local change
- 9ConnectionChoose how long a setting lasts
- 10ExplanationSearch for an external command
- 11ExampleAppend a personal directory
- 12Key InsightA slash selects a location directly
- 13ChallengePreserve the earlier winner
- 14ChallengeConnect recall, quoting, and lookup
- 15RecapTrack text, values, and scope
Linux Command Line practice questions
Set 1: Read commands, help, and paths10 Practice Questions
Question 1 of 10
/home/sam/labs/module. What absolute directory does cd ../../downloads select?Show answerHide answer
.. reaches /home/sam/labs, and the second reaches /home/sam. The final component then enters its downloads child. Stopping after only one parent would incorrectly put the destination inside labs; the two parent components must both be followed.Question 2 of 10
assets itself, without listing the files inside it. What command does that?Show answerHide answer
-d option tells ls to display the directory entry itself, and -l adds its metadata. Without -d, ls -l assets lists entries inside that directory. Adding hidden or recursive options changes the contents view but does not select the directory's own entry.Question 3 of 10
mkdir [OPTION]... DIRECTORY.... What is required for a basic valid invocation?Show answerHide answer
Question 4 of 10
sam@laptop:~/training$ and is ready for input. What location does the prompt indicate?Show answerHide answer
/training names its child. The prompt therefore indicates /home/sam/training. Reading only the tilde would miss the child component and incorrectly place the shell at home.Question 5 of 10
Show answerHide answer
ls separates the command from its option, and the quotes keep the file name in one argument. Without quotes, Bash supplies two separate names, Team and Schedule.pdf. Adding slashes would describe a different path instead of protecting the space.Question 6 of 10
Show answerHide answer
Question 7 of 10
/etc/passwd, but man passwd opens the password-changing command. What command opens the needed page?Show answerHide answer
passwd. Section 1 is the user-command page that already opened. A keyword search or one-line description can identify pages but does not select the requested format reference directly.Question 8 of 10
type export reports that export is a shell built-in. How can you read Bash's help for it?Show answerHide answer
help, so help export targets this command directly. Applying an external program's usual --help pattern is unreliable for built-ins. The command kind reported by type tells you which help system to consult.Question 9 of 10
ls shows nothing in settings, but ls -A settings shows .localrc. Why do the results differ?Show answerHide answer
-A includes such entries. The listing option does not create files or grant extra access. An empty ordinary listing can therefore coexist with a nonempty directory containing hidden names.Question 10 of 10
/home/sam, you run cd projects, then ls ../downloads, then cd ../photos. All named directories exist. What directory are you in, and what does cd - select next?Show answerHide answer
/home/sam/projects; listing ../downloads does not change that location. The final relative change goes up to sam and into photos. cd - returns to the previous working directory, projects, not to the directory merely listed.Set 2: Predict changes to files and directories10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
lab does not exist. How can you create lab/week2/input and its missing parents in one command?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
records contains jan.csv, and stored already exists as an empty directory. What path contains the copied file after cp -r records stored?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
agenda.txt contains meeting notes. What happens when you run touch agenda.txt?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
rough.txt exists and archive does not. What does unaliased mv rough.txt archive do?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
old-cache is a directory that should be empty. What command removes it only if that expectation is correct?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
-scratch.log. How can unaliased GNU rm receive that name without reading it as options?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
unit/part contains only .prefs. Why does rmdir unit/part fail even though plain ls unit/part looks empty?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
/home/sam, source/item.txt exists and saved is an empty directory. You run cp -r source saved, then mv saved/source saved/session. Where are the original and copied files now?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
/home/sam/work, ../safe is an empty directory, and part contains only keep.txt. You run cp part/keep.txt ../safe/, mv part/keep.txt keep.txt, then rmdir part. What remains?Show answerHide answer
Save this lesson to see this answer.
Set 3: Match names and use shell values10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
task.txt, task4.txt, and task42.txt. What name matches task?.txt?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
.zip entries in the working directory. What does echo *.zip print?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
upload, inspect it, and edit it before running. What feature is suited to finding it?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
folder="Project Plans", what argument does ls "$folder" receive for the path?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
rec1.csv, rec2.csv, rec3.csv, and rec12.csv. What names match rec[!2].csv?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
/opt/team/bin:/usr/bin:/bin. Both the first two directories contain an executable named report. No alias, function, or built-in has that name. What runs?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
pic1.png and pic2.png. What does echo "pic*.png" print?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
region is unset. You run region=west, then bash -c 'echo $region'. Why does the child shell print an empty line?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
item1.dat, item2.dat, item12.dat, .item3.dat, plus an empty out directory. You run cp item?.dat out/, then mv out/item2.dat out/chosen.dat. What files are in out?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
/usr/bin:/bin. There are executable files /usr/bin/scan and /home/sam/bin/scan, with no shell-defined scan. You run export PATH="$PATH:$HOME/bin" with HOME /home/sam. What runs for scan and for ./scan from /home/sam/bin?Show answerHide answer
Save this lesson to see this answer.
Set 4: Connect paths, patterns, and command behavior10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
red1.tmp, red2.tmp, red10.tmp, and an empty save directory. After cp red[12].tmp save/ and mv save/red1.tmp save/final.txt, what does echo save/*.tmp print?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
checkup is in your current directory, which is absent from PATH. There is no other command with that name. How can you run this file?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
ls reports unrecognized option '--time-sort'. What is the most direct next check for the installed GNU program?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
. and ... What GNU command provides it?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
-d, --date=STRING. In touch --date=2026-02-18 checkpoint, what role does 2026-02-18 have?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
clip.jpg, clip.JPG, clip.Jpg, and clip.jpeg. What names match clip.[jJ][pP][gG]?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
!cp without running it. What history expression prints the expansion only?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
/home/sam/jobs/run, ../data holds a.txt, and /home/sam/store already exists. You run cp -r ../data ../../store/, then mv ../../store/data/a.txt ../../store/data/b.txt. What new path holds the copy, and where is the source?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
area was unset. You run area=north, export area, bash, then inside the child area=south and exit. What does echo "$area" print back in the parent, and why?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
/home/sam/team/drafts, you run cd ../final, then cd -, then ls ../../photos. All directories exist. Where are you, and what directory did the listing inspect?Show answerHide answer
Save this lesson to see this answer.
Set 5: Resolve several command-line decisions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
tag=blue, what does echo '$tag' print?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
bundle does not exist. You run mkdir -p bundle/raw bundle/log, touch bundle/raw/x, mv bundle/raw/x bundle/log/, then rmdir -p bundle/raw. What remains under bundle?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
touch note{2..4}.txt, mkdir bin, mv note[24].txt bin/, then echo note?.txt. What is printed?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
/usr/bin:/bin, HOME is /home/sam, and executable render files exist in /usr/bin and /home/sam/bin. No alias, function, or built-in is named render. After export PATH="$HOME/bin:$PATH", what external file does bare render select, and what is the full resulting PATH?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
-review notes.txt. What single GNU ls command requests its details while handling both the leading dash and the space?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
unit1.tmp, unit2.tmp, unit10.tmp, .unit3.tmp, and final.txt, all regular files. After previewing, you run unaliased rm -i unit?.tmp and answer y to every prompt. What regular files remain?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
mkdir -p samples/day7, you run pwd, then echo !$. What does the history shortcut select?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
/home/sam, projects contains only .prefs and a directory src; src holds main.c. The directory archive exists and is empty. You run ls projects, cp -r projects/src archive/, mv projects/src archive/live, then rmdir projects. What remains in projects and archive?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
/home/sam, you set dest="$HOME/Field Notes" and export dest. A child Bash runs cd "$dest", then changes dest=elsewhere and exits. The directory exists. What path did the child enter, and what is the parent's dest value afterward?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Absolute path
/ and describes a location from the root directory, so its meaning does not depend on your current location./home/sam/photos identifies the same directory whether the shell is currently in /etc or in sam's home.Alias
ls as ls --color=auto; type ls reveals that extra command text.apropos
apropos directory helps identify mkdir or rmdir when you remember the task but not the command name.Archive copy
cp -a that preserves file attributes, making it useful for copying a directory tree.cp -a site site-backup retains the tree's attributes instead of treating it as an ordinary fresh file copy.Argument
cp report.txt saved/, the two path arguments identify the source file and the destination directory.B
Bash
help cd directly because cd is one of its built-ins, not a separate program file.Bash help
help followed by a built-in's name.help export explains exporting variables, while help by itself lists the available built-ins.Brace expansion
file{1..3}.txt.mkdir work/{src,docs} receives two generated directory names, even when neither child exists yet.Bracket expression
! or ^ negating that set.part[13].txt matches the names ending in 1 or 3 at that position, but not the two-digit ending 13.Built-in
type cd reports a built-in, and help cd gives the documentation for Bash's directory-changing command.C
Case sensitivity
Plans and plans can identify different directories; completion helps preserve the correct case.Character class
[[:digit:]] for digits or [[:lower:]] for lowercase characters.Command
ls -l /var, the command name is ls; the remaining words control and target the listing.Command history
Command lookup
type echo can report Bash's built-in before an external echo file that also exists in a PATH directory.Copy
cp.cp memo.txt stored/ creates stored/memo.txt when stored exists, leaving the original memo where it was.D
Destination
archive absent, mv notes.txt archive uses archive as a new file name instead of making a directory.Directory
/home/sam/projects can hold both notes.txt and a child directory named website.E
Environment
Environment variable
export.export city lets a later child Bash read the city value that was previously held only in the parent.Error message
No such file or directory message from ls suggests checking the path, case, and working directory.Executable
./backup when its directory is absent from PATH.Expansion preview
ls -d -- draft* displays the matching entries themselves, so matched directories are visible as targets.Explicit command path
/home/sam/bin, ./backup and /home/sam/bin/backup both identify the same local executable.export
F
File
.pdf.Force option
-f in GNU rm, suppresses confirmation and ignores missing names, increasing the need to verify the target expression.-f does not supply a recovery path; it only changes how removal handles questions and missing names.G
Globbing
ls *.log receives two file names rather than receiving the literal star pattern.H
Hidden entry
ls output to omit it by default..bashrc appears with ls -a, even though a plain home-directory listing skips it.HISTCONTROL
ignoreboth combines ignorespace and ignoredups; an arbitrary shell may use a different setting.History expansion
!! for the preceding command.mkdir drafts, cd !$ reuses the last argument, but another intervening command changes it.History file
~/.bash_history, with its path held in HISTFILE.Home directory
/home/username for an ordinary Linux user.~ expands to /home/sam; /home alone is the directory containing users' homes.Human-readable size
ls -h.-h with -l: the former formats sizes, while the latter provides the column that displays them.I
Info manual
info coreutils opens a longer manual; n, p, and u move among its linked nodes.Interactive removal
rm -i asking separately for each target.rm -i *.tmp asks about the matching names before removing them.L
Literal pattern
echo "*.txt" prints the star and suffix even when the directory contains files that would match them.Locale
Long listing
ls -l, showing metadata such as type, ownership, size, and modification time.ls -l notes.txt shows a single file's details; adding -h changes a byte size such as 2048 to 2.0K.M
Manual page
man ls opens the listing command's reference, where you can search for an option you need.Manual section
man 5 passwd selects the file-format page instead of the command.Metadata
mkdir
-p option creates missing parents and accepts path components already present as directories.mkdir -p app/css prepares both directories when app is missing, so a file can later be created inside css.Modification time
ls -t uses it to sort entries newest first.touch updates this timestamp without changing the file's data, so it can change time-based order.Move
mv without the recursive option required for copying a tree.mv memo.txt stored/ puts the existing file into stored, so its old path no longer names that moved file.O
Option
-l option tells ls to show a long listing with details instead of displaying only names.Overwrite
cp or mv can do without asking.cp -i notes.txt saved.txt to ask before replacing saved.txt when a file with that name already exists.P
Package documentation
/usr/share/doc/ in a directory for that package./usr/share/doc/bash can reveal README files, change logs, license text, and examples.Pager
man pager lets you search with /size, move through matches with n, and quit with q.Parent directory
.. refers to that parent./home/sam/projects/website, one .. reaches projects, while two reach sam's home.PATH
/.:$HOME/bin preserves earlier directories and their priority when a program name appears twice.Path component
/.data/*.csv selects directly inside data; it does not also select matching names under data/old.Prompt
sam@laptop:~$, the tilde indicates home and the final dollar sign commonly indicates an ordinary user.Q
Quick help
--help.mkdir --help to find the parent-creation option without navigating the full manual page.Quoting
ls "Work Plan.txt" keep the space inside the file name instead of splitting it into two words.R
Recursive listing
ls -R projects shows projects: and then headings for child directories such as projects/website:.Recursive removal
rm -r.rmdir old-cache when an unexpected child should stop cleanup instead of being deleted along with its parent.Relative path
/home/sam/projects, ../photos reaches sam's photos directory by going up and then down.Reverse search
rm
rm -i old.txt requests confirmation before removing that file, allowing you to decline the action.rmdir
rmdir cache reports nonempty contents but plain ls looks blank, use ls -A cache to check hidden entries.Root account
# conventionally signals root; ordinary work should use an ordinary account.Root directory
/, is the starting point of Linux's single file-system tree, above every other absolute path./etc begins at the root directory; it does not name a child of your current working directory.S
Search priority
/usr/bin.Shell
pwd in a terminal session and prints the directory where the shell is working.Shell variable
city=Lisbon alone does not provide that value to a new child Bash unless city is already exported.Source
cp and mv forms.cp notes.txt archive/, notes.txt supplies the data and archive/ identifies where its copy should go.Startup file
~/.bashrc is read by a new interactive non-login Bash; a login profile may load that file too.SYNOPSIS
mkdir [OPTION]... DIRECTORY... permits optional switches but requires at least one directory name.T
Terminal
Tilde expansion
~ at the start of a shell word with a home path, making home-based paths convenient to type.cd ~/Documents reaches your documents from anywhere, but quoting the tilde prevents that substitution.Timestamp
touch -d 2025-01-31 old.txt requests a chosen date instead of using the current time for the update.touch
touch checklist.txt keeps an existing checklist's text; it does not clear the file before updating its times.U
Unmatched glob
echo *.pdf prints the pattern while ls *.pdf reports that literal path missing.V
Variable
name=value and read through expansion such as $name.topic=linux, echo "$topic" prints the stored value, while unset topic removes the variable.Variable expansion
echo "${city}_trip" appends text to city's value, while $city_trip would read a different variable name.W
whatis
whatis ls gives a short purpose statement; man ls supplies the longer reference when more detail is needed.Wildcard
* for a sequence or ? for one character.part?.txt accepts part4.txt but excludes a name with two digits in the question mark's position.Working directory
cd projects, the relative name notes.txt refers to a file inside that newly selected directory.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.