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-lor--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/logHere, 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 directoryNavigating 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/projectsPaths containing spaces must be quoted or escaped:
cd "Project Files"
cd Project\ Filesls 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| Command | Primary purpose | Common options | Example | Safety note |
|---|---|---|---|---|
pwd | Print current directory | Usually none | pwd | Safe; use before path-sensitive operations. |
cd | Change directory | ~, .. | cd ../logs | Check spelling and quoting. |
ls | List contents | -l -a -h -R | ls -lah | Listing is safer than guessing names. |
mkdir | Create directories | -p | mkdir -p work/data | Verify the destination first. |
touch | Create an empty file or update its timestamp | None commonly needed | touch notes.txt | It can change an existing file's timestamp. |
cp | Copy files | -r, -i, -v | cp -i a.txt backup.txt | Check whether the destination exists. |
mv | Move or rename | -i, -v | mv old.txt new.txt | It may overwrite a destination. |
rm | Remove files | -i
dash -r | rm -i notes.txt | Removal normally bypasses a graphical trash bin. |
rmdir | Remove empty directories | None commonly needed | rmdir empty-dir | It 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 -lamkdir -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.txtCopy 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-projectsrm filename removes a file. rmdir removes only an empty directory. Recursive deletion removes a directory and its contents:
rm -ri archived-projectsThe -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.txtFor 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/passwdhead 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/passwdtail -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/syslogfile 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| Command | Use case | Useful options | Input and output behavior | Example |
|---|---|---|---|---|
cat | Display small files | -n | Reads files and writes content to standard output. | cat notes.txt |
less | Read interactively | Search and navigation keys | Opens a paginated viewer. | less /etc/passwd |
head | Inspect the beginning | -n 5 | Writes selected initial lines. | head -n 5 file |
tail | Inspect the end or follow logs | -n, -f | Writes final lines or waits for appended lines. | tail -f app.log |
grep | Search text | -i -n -R -v | Reads files or standard input and prints matching lines. | grep -n 'bash' file |
find | Locate filesystem objects | -type -name | Traverses a starting directory and prints matches. | find . -type f -name '*.log' |
file | Identify file type | None commonly needed | Reads identifying information and reports it. | file image.bin |
wc | Count lines, words, or bytes | -l -w -c | Reads 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.confQuote patterns when they contain spaces or characters meaningful to the shell:
grep -i 'error: failed' application.logGlobbing 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].pnggrep 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 *.txtStandard 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.
| Syntax | Meaning | Example | Result |
|---|---|---|---|
> | Overwrite standard output | ls > listing.txt | Creates or replaces the file. |
>> | Append standard output | date >> listing.txt | Adds output at the end. |
< | Use a file as standard input | wc -l < listing.txt | The command reads from the file. |
2> | Redirect standard error | find / -name x 2> errors.txt | Diagnostics go to a separate file. |
2>&1 | Send standard error where standard output currently goes | command > all.txt 2>&1 | Both streams go to all.txt. |
| | Pipe output into another command | grep bash /etc/passwd | wc -l | Counts 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 -lRedirection 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.shThe 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 otherRead (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.
| Symbol or digit | Permission | Effect on files | Effect on directories |
|---|---|---|---|
r / 4 | Read | Read contents | List names |
w / 2 | Write | Modify contents | Create, delete, or rename entries when permitted |
x / 1 | Execute | Run as a program when valid | Enter and access entries |
u | User | The file owner class | |
g | Group | The associated group class | |
o | Other | All 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.txtNumeric notation adds values: read is 4, write is 2, and execute is 1. Add the values for user, group, and other in that order.
| Mode | Symbolic equivalent | Typical use | Caution |
|---|---|---|---|
644 | rw-r--r-- | Ordinary readable file | Others can read it. |
600 | rw------- | Private file | Other users cannot read it. |
755 | rwxr-xr-x | Executable script or public directory | Others can read and execute. |
700 | rwx------ | Private executable or directory | Only the owner has access. |
ls -l script.sh
chmod u+x script.sh
ls -l script.sh
chmod 644 notes.txt
chmod 755 script.shOwnership 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 filenameFor 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 informationdf 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
- Work inside a temporary directory under your home directory, such as
~/linux-practice. - Run
pwdto confirm where you are. - Run
ls -lato inspect names and hidden entries. - Use quoted paths when names contain spaces.
- Prefer
-iand-voptions while learning. - Check the destination before
cpormv. - Check the complete target before
rmorrm -r. - 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 -lFor further study, explore Less Text Viewer 2, Check Disk Space 2, and Hard Links 2.