Unit

Essential Linux Commands 2

Learn intermediate Linux commands for navigating, inspecting, organizing, searching, and processing files safely from the command line.

This lesson builds on basic terminal use. You will learn how to navigate the filesystem, manage files, inspect text, search for information, connect commands with pipelines, understand permissions, and work more safely at the command line.

Command-line review and shell conventions

A terminal is the text-based interface in which you work. A shell is the command interpreter running inside the terminal. The shell reads your command, expands certain patterns, and starts a program or shell builtin.

A typical command has this structure:

command options arguments
  • Command: the program or shell builtin to run, such as ls.
  • Option: a modifier beginning commonly with - or --, such as -l or --help.
  • Argument: a value supplied to the command, often a filename, path, or search pattern.
  • Path: a location identifying a file or directory.
ls -lah /var/log

Here, ls is the command, -lah contains options, and /var/log is an argument and absolute path.

Absolute and relative paths

An absolute path starts at the root directory, written /. For example, /home/alex/projects identifies the same location regardless of your current directory. A relative path is interpreted from the current working directory, such as projects/report.txt.

The current working directory is the directory commands use when you do not provide an absolute location. The special path . means the current directory, and .. means its parent. The tilde ~ represents your home directory.

pwd                 # Show the current directory
ls .                # List the current directory
ls ..               # List the parent directory
cd ~                # Go to your home directory
cd /                # Go to the root directory

Navigating the filesystem

pwd, cd, and ls

pwd prints the present working directory. cd changes it. With no argument, cd returns to your home directory.

pwd
cd /var/log
cd ..
cd ~
cd ~/linux-practice/projects

Paths containing spaces must be quoted or escaped:

cd "Project Files"
cd Project\ Files

ls lists directory contents. Important options include:

  • -l: long format, including permissions, ownership, size, and modification time.
  • -a: include hidden files, whose names begin with a period.
  • -h: show sizes in human-readable units when used with long format.
  • -R: list subdirectories recursively.
ls -lah
ls -l /etc/passwd
ls -R ~/linux-practice
Core navigation and file-management commands
CommandPrimary purposeCommon optionsExampleSafety note
pwdPrint current directoryUsually nonepwdSafe; use before path-sensitive operations.
cdChange directory~, ..cd ../logsCheck spelling and quoting.
lsList contents-l -a -h -Rls -lahListing is safer than guessing names.
mkdirCreate directories-pmkdir -p work/dataVerify the destination first.
touchCreate an empty file or update its timestampNone commonly neededtouch notes.txtIt can change an existing file's timestamp.
cpCopy files-r, -i, -vcp -i a.txt backup.txtCheck whether the destination exists.
mvMove or rename-i, -vmv old.txt new.txtIt may overwrite a destination.
rmRemove files-i dash -rrm -i notes.txtRemoval normally bypasses a graphical trash bin.
rmdirRemove empty directoriesNone commonly neededrmdir empty-dirIt refuses non-empty directories.

Creating and organizing files

Create a safe workspace in your home directory:

mkdir -p ~/linux-practice/projects
cd ~/linux-practice
pwd
ls -la

mkdir -p creates missing parent directories. touch creates an empty file if it does not exist.

touch notes.txt
cp notes.txt notes-backup.txt
mv notes-backup.txt archive.txt
rm archive.txt

Copy a directory and its contents with cp -r. Use mv both to move and rename files or directories:

cp -r projects projects-copy
mv projects-copy archived-projects

rm filename removes a file. rmdir removes only an empty directory. Recursive deletion removes a directory and its contents:

rm -ri archived-projects

The -i option asks questions before removal. Never use recursive deletion until you have verified the complete target path and contents. Options such as -i and -v are useful while learning. Copy and move commands can overwrite existing destinations, so interactive forms such as cp -i and mv -i are safer for practice.

Viewing and inspecting file contents

Use cat for a small text file:

cat notes.txt

For longer text, less displays one screen at a time. Use the arrow keys or Page Up and Page Down to move, type /pattern to search, and press q to quit.

less /etc/passwd

head shows the beginning and tail shows the end. The default is commonly ten lines; specify a count with -n.

head -n 5 /etc/passwd
tail -n 5 /etc/passwd

tail -f follows a changing file and prints new lines as they arrive. Stop it with Ctrl+C. Log locations vary by distribution, so use a readable log available on your system:

tail -f /var/log/syslog

file identifies content type rather than relying only on a filename extension. wc counts lines, words, and bytes; -l, -w, and -c select a particular count.

file notes.txt
wc notes.txt
wc -l /etc/passwd
Text inspection and search commands
CommandUse caseUseful optionsInput and output behaviorExample
catDisplay small files-nReads files and writes content to standard output.cat notes.txt
lessRead interactivelySearch and navigation keysOpens a paginated viewer.less /etc/passwd
headInspect the beginning-n 5Writes selected initial lines.head -n 5 file
tailInspect the end or follow logs-n, -fWrites final lines or waits for appended lines.tail -f app.log
grepSearch text-i -n -R -vReads files or standard input and prints matching lines.grep -n 'bash' file
findLocate filesystem objects-type -nameTraverses a starting directory and prints matches.find . -type f -name '*.log'
fileIdentify file typeNone commonly neededReads identifying information and reports it.file image.bin
wcCount lines, words, or bytes-l -w -cReads files or standard input and prints counts.wc -l file

Searching for files and text

find

find searches from a starting path. Quote filename patterns so the shell does not expand them before find receives them.

find ~/linux-practice -type f -name '*.txt'
find ~/linux-practice -type d -name 'projects'
find . -type f -name '*.log'

Other useful tests include -iname for case-insensitive names and -size for size-based searches. Permission errors usually mean the search entered a directory your user cannot read. Limit the starting path or redirect expected diagnostics with 2>; do not use sudo merely to hide an unclear problem.

grep

grep searches text and prints matching lines. Common options are -i for case-insensitive matching, -n for line numbers, -R for recursive searching, and -v for inverted matching, which prints nonmatching lines.

grep -n 'bash' /etc/passwd
grep -i 'bash' /etc/passwd
grep -Rin 'pattern' ~/linux-practice
grep -v '^#' configuration.conf

Quote patterns when they contain spaces or characters meaningful to the shell:

grep -i 'error: failed' application.log

Globbing versus grep patterns

A glob is a filename pattern expanded by the shell before a command runs. In a glob, * matches any sequence of filename characters, ? matches one character, and a character class such as [ab] matches one listed character.

ls *.txt
echo report?.log
echo image[1-3].png

grep patterns are interpreted by grep, not as filename globs. They commonly use regular-expression rules. Thus, *.txt passed to find -name should be quoted, while *.txt used with ls is normally intended for shell expansion. Use echo to observe what the shell expands:

echo *.txt

Standard streams, redirection, and pipelines

Every command conventionally has three streams: standard input (file descriptor 0) supplies input, standard output (descriptor 1) carries normal results, and standard error (descriptor 2) carries diagnostic messages. Redirection sends a stream to or from a file. A pipeline connects commands with |, passing one command's standard output to the next command's standard input.

Redirection and pipeline operators
SyntaxMeaningExampleResult
>Overwrite standard outputls > listing.txtCreates or replaces the file.
>>Append standard outputdate >> listing.txtAdds output at the end.
<Use a file as standard inputwc -l < listing.txtThe command reads from the file.
2>Redirect standard errorfind / -name x 2> errors.txtDiagnostics go to a separate file.
2>&1Send standard error where standard output currently goescommand > all.txt 2>&1Both streams go to all.txt.
|Pipe output into another commandgrep bash /etc/passwd | wc -lCounts matching lines.

The difference between > and >> is important: > replaces existing contents, while >> appends.

ls -la > directory-report.txt
date >> directory-report.txt
cat directory-report.txt
grep -i 'bash' /etc/passwd | wc -l
find ~/linux-practice -type f -name '*.txt' | wc -l

Redirection order matters. In command > all.txt 2>&1, standard output is assigned to the file first, then standard error is directed to the same destination.

Permissions and ownership basics

Reading ls -l

A long listing may begin like this:

-rwxr-x--- 1 alex developers 1200 Aug 18 10:30 script.sh

The first character identifies the object type: - is a regular file and d is a directory. The next nine characters are three groups of permissions: user (owner), group, and other.

-   rwx   r-x   ---
|    |     |     |
type user  group other

Read (r) allows reading file contents. For a directory, it allows listing names. Write (w) allows changing file contents. For a directory, it allows creating, deleting, or renaming entries, subject to other directory permissions. Execute (x) allows running a file when appropriate. For a directory, it allows entering it and accessing entries whose names are known.

Linux permission notation
Symbol or digitPermissionEffect on filesEffect on directories
r / 4ReadRead contentsList names
w / 2WriteModify contentsCreate, delete, or rename entries when permitted
x / 1ExecuteRun as a program when validEnter and access entries
uUserThe file owner class
gGroupThe associated group class
oOtherAll other users

chmod, ownership, and numeric modes

chmod changes permissions. Symbolic notation identifies a class and adds or removes permissions:

chmod u+x script.sh
chmod g-w shared.txt
chmod o-r private.txt

Numeric notation adds values: read is 4, write is 2, and execute is 1. Add the values for user, group, and other in that order.

Common permission modes
ModeSymbolic equivalentTypical useCaution
644rw-r--r--Ordinary readable fileOthers can read it.
600rw-------Private fileOther users cannot read it.
755rwxr-xr-xExecutable script or public directoryOthers can read and execute.
700rwx------Private executable or directoryOnly the owner has access.
ls -l script.sh
chmod u+x script.sh
ls -l script.sh
chmod 644 notes.txt
chmod 755 script.sh

Ownership associates an object with a user and group. Inspect it with ls -l or id. chown changes the owner, and chgrp changes the group. These operations often require elevated privileges and should not be used casually.

chown user:group filename
chgrp developers filename

For a focused explanation, see Modify File Permissions 2.

System and user information

whoami                 # Current username
id                     # User and group IDs and memberships
who                    # Logged-in users
w                      # Logged-in users and activity
date                   # Current date and time
df -h                  # Filesystem free and used space
du -sh ~/linux-practice  # Space used by a directory
which ls               # Locate an executable
command -v grep        # Shell-aware executable or builtin lookup
man find               # Full manual page
find --help            # Concise usage information

df reports usage by mounted filesystem. du reports space used by files and directories. The -h option makes sizes easier to read; du -sh directory gives one summary for a directory.

command -v is often preferable to which because it can also identify shell builtins, aliases, or functions depending on the shell. Use man command_name for detailed documentation and command_name --help for a quick syntax summary.

Command history and shell productivity

history displays previously entered commands. Use the Up and Down arrow keys to recall commands, edit them, and press Enter to run the edited version. In many shells, Ctrl+R searches backward through history.

history
history | tail
!!
!42

!! repeats the previous command and !42 recalls a numbered entry. Review recalled commands carefully before executing them, especially if they contain rm, redirection, wildcards, or sudo.

Tab completion fills in commands, filenames, and directories where supported. It reduces typing and helps reveal the exact spelling and capitalization of names.

Quote or escape names containing spaces and special characters:

cat 'meeting notes.txt'
cat meeting\ notes.txt
mkdir 'January Reports'

Single quotes preserve the characters inside them literally. Double quotes also protect spaces, while still allowing some shell expansions. A backslash escapes the next character.

Safe practice workflow

  1. Work inside a temporary directory under your home directory, such as ~/linux-practice.
  2. Run pwd to confirm where you are.
  3. Run ls -la to inspect names and hidden entries.
  4. Use quoted paths when names contain spaces.
  5. Prefer -i and -v options while learning.
  6. Check the destination before cp or mv.
  7. Check the complete target before rm or rm -r.
  8. Use extra care with sudo: it runs a command with elevated privileges, which can affect system files and other users' data.

Troubleshooting common problems

cd says “No such file or directory”

Run pwd, then ls -la. Check spelling and capitalization. If the name contains spaces, quote it or escape the spaces. Use an absolute path when you are unsure of the starting directory.

rm cannot remove a directory

The target is a directory, or it is not empty. Inspect it with ls -ld target. Use rmdir only when it is empty. Use recursive deletion only after verifying the path and contents.

Permission denied when running a script

Check ls -l script.sh. If appropriate, add execute permission with chmod u+x script.sh. You can sometimes run a script through its interpreter, for example bash script.sh, without making the file directly executable. Parent-directory permissions and filesystem mount settings can also prevent execution.

grep finds no matches

Confirm the file with head or less. Try grep -i if capitalization may differ. Search the correct file or directory, and quote patterns containing spaces or special characters.

Redirection replaced a file

> overwrites; >> appends. Inspect the output filename and operator before pressing Enter. During practice, use a new report filename.

find reports permission errors

Restrict the search to directories you can read, or redirect irrelevant diagnostics with 2> errors.txt. Do not use sudo simply to conceal an unexplained access problem.

A wildcard behaves unexpectedly

The shell may expand an unquoted glob before the command receives it. Use echo pattern to observe expansion. Quote patterns intended for find -name, while leaving filename globs unquoted when you want the shell to expand them.

Practice sequence

Run these commands in the practice directory and verify the result after each group:

mkdir -p ~/linux-practice/projects
cd ~/linux-practice
pwd
ls -la
touch notes.txt
cp notes.txt notes-backup.txt
mv notes-backup.txt archive.txt
ls -l
rm archive.txt
ls -l
ls -la > directory-report.txt
date >> directory-report.txt
cat directory-report.txt
find ~/linux-practice -type f -name '*.txt'
grep -i 'bash' /etc/passwd | wc -l

For further study, explore Less Text Viewer 2, Check Disk Space 2, and Hard Links 2.