E-NO
Linux commands 11 Min Read

Linux Basic Commands with Practical Examples

calendar_today Published: 2026-08-08
update Last Updated: 2026-08-12
analytics SEO Efficiency: 100%
Technical guide illustration for Linux Basic Commands with Practical Examples.

This guide gives operators and developers a practical path to the most useful Linux commands. You will set up a safe lab in your home directory, practice file and process operations, verify outcomes with checksums and listings, and learn to recover from common mistakes. All examples favor non-destructive flags and reversible steps, so you can build muscle memory with confidence.

Who This Helps

  • Developers who need reliable day-to-day shell usage.
  • DevOps consultants who teach or standardize team practices.
  • Startup teams that want consistent, low-risk operations habits.

What You Will Achieve

  • A safe practice area under your home directory.
  • Command patterns for navigation, inspection, file management, permissions, search, process monitoring, and archiving.
  • Verification steps that prove your changes worked.
  • Recovery techniques for common failure modes.

Constructed examples are clearly labeled. Do not run commands with elevated privileges unless required and understood.

Version and Environment Inventory

Before running any command, confirm what you are working on. Small differences in shell, distribution, and permissions can change behavior. Record the following. The example outputs are constructed examples.

uname -r
grep '^PRETTY_NAME' /etc/os-release
echo $SHELL
bash --version | head -1
echo $PATH
echo $HOME; pwd
umask; id
df -h "$HOME" | awk 'NR==2 {print $4}'

Constructed example outputs (yours will differ):

WhatCommandExample output
Kerneluname -r5.15.0-123-generic
Distributiongrep '^PRETTY_NAME' /etc/os-releasePRETTY_NAME="Ubuntu 22.04 LTS"
Shellecho $SHELL/bin/bash
Bash versionbash --versionGNU bash, version 5.1.x
PATHecho $PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Disk free under $HOMEdf -h "$HOME"42G free

Safe Configuration Path

The safest way to learn is to operate in a disposable lab within your home directory and use safeguards that require confirmation or allow rollback.

1) Create a Disposable Lab

LAB="$HOME/tmp/linux-basic-commands-lab"
mkdir -p "$LAB"
cd "$LAB"
pwd

Expected: pwd shows your lab path. If the directory already existed, mkdir -p is safe and does not overwrite.

Initialize sample content:

# Create files and directories for practice
mkdir -p docs src bin data
printf "alpha\nbeta\ngamma\n" > data/greek.txt
printf "one\ntwo\nthree\n" > data/numbers.txt
printf "user: x:1000:1000: User,,,:/home/user:/bin/bash\n" > data/passwd.sample
printf "#!/usr/bin/env bash\necho Hello" > bin/hello.sh
chmod +x bin/hello.sh

Verification:

ls -l
ls -l data bin

Expected: directories exist, files present, bin/hello.sh is executable (x flag set for your user).

2) Navigate and Inspect Safely

  • Print working directory: pwd
  • List with details and human sizes: ls -alh
  • Show most recent files first: ls -lt
  • Limit depth with find to avoid surprises: find . -maxdepth 2 -type f -printf '%p\n'
  • View file content without flooding your terminal: head -n 5 file, tail -n 5 file, less file (quit with q)

Examples:

pwd
ls -alh
find . -maxdepth 2 -type f -print
head -n 2 data/greek.txt

Expected: clear listings and first lines from greek.txt.

3) Create, Copy, Move, and Remove with Safeguards

Safer flags and habits:

  • Use -i (interactive) with cp, mv, rm to confirm overwrites or deletions.
  • Use -- to end option parsing when filenames start with dashes.
  • Quote paths with spaces: "My File.txt".
  • Make a quick backup before edits: cp -a file{,.bak}.

Examples:

# Copy without overwriting existing files
cp -ai data/greek.txt docs/
cp -ai data/numbers.txt docs/

# Move a file, prompting if destination exists
mv -i docs/greek.txt docs/greek.list

# Create a file safely, refuse to overwrite an existing one
touch -- greek.new

# Remove with prompt (y to delete, n to cancel)
rm -i docs/greek.list

Verification:

ls -l docs
test -f docs/numbers.txt && echo OK || echo MISSING

Expected: docs contains numbers.txt; greek.list removed if you confirmed deletion.

4) Permissions You Can Reverse

Operate only inside $LAB.

# Show permission bits
ls -l bin/hello.sh

# Remove your write bit and demonstrate failure
chmod u-w bin/hello.sh
ls -l bin/hello.sh
# Attempt to append should fail with Permission denied
echo '# more' >> bin/hello.sh || echo 'as expected: Permission denied'

# Restore write bit
chmod u+w bin/hello.sh
ls -l bin/hello.sh

Expected: chmod toggles the user write bit; append fails when u-w is set; succeeds again after restoring.

Check umask for default file perms:

umask

Typical values: 0022 or 002. Keep note for later troubleshooting.

5) Search and Filter Text Safely

  • Search text recursively: grep -R --line-number --color=auto PATTERN PATH
  • Match whole words: grep -Rw "\<word\>" PATH
  • Count lines or matches: wc -l file, grep -c PATTERN file
  • Sort and count unique lines: sort file | uniq -c | sort -nr

Examples:

# Find occurrences of digits in data
grep -R --line-number '[0-9]' data

# Count lines in greek.txt
wc -l data/greek.txt

# Show unique lines across data files
cat data/*.txt | sort | uniq -c | sort -nr

Expected: numbers.txt lines matched; greek.txt has 3 lines; unique counts are shown.

6) Process and System Inspection

  • List your processes: ps -u "$USER" -o pid,ppid,cmd --sort=pid
  • System-wide full-format: ps -ef | head
  • Find processes by name: pgrep -af pattern
  • Show memory and CPU quick view: top (quit with q)
  • Disk usage summary: df -h (filesystems) and du -sh "$LAB" (directory)

Examples:

ps -u "$USER" -o pid,ppid,cmd --sort=pid | head
pgrep -af bash
free -h || cat /proc/meminfo | head -5
df -h | head
du -sh "$LAB"

Expected: running shells and memory/disk summaries appear. If free is not available, /proc/meminfo provides details.

7) Archiving and Checksums

  • Create a tar archive: tar -czf archive.tgz DIR
  • List archive contents: tar -tzf archive.tgz | head
  • Extract: tar -xzf archive.tgz -C DEST
  • Generate checksums: sha256sum file

Examples:

# Snapshot the lab
cd "$LAB"
tar -czf lab-snapshot.tgz .
sha256sum lab-snapshot.tgz > lab-snapshot.tgz.sha256

# Verify checksum
sha256sum -c lab-snapshot.tgz.sha256

# Inspect archive contents without extracting
tar -tzf lab-snapshot.tgz | head

Expected: checksum verification reports OK; archive listing shows your files and directories.

8) Redirection and Pipelines Without Surprises

  • Append instead of overwrite: >> (safer). If you must overwrite, consider a backup first.
  • Protect from clobbering with: set -o noclobber (within your current shell session), then use >| to force overwrite only when intended.

Examples:

set -o noclobber
printf 'safety-first\n' > data/safety.txt
# The next overwrite should fail due to noclobber
printf 'oops\n' > data/safety.txt || echo 'as expected: cannot overwrite'
# Force overwrite intentionally
printf 'overwrite\n' >| data/safety.txt
set +o noclobber

Verification:

tail -n 1 data/safety.txt

Expected: final line is "overwrite" after the forced overwrite.

9) Safer Use of Find for Bulk Changes

Preview with print, then apply using -exec only after review.

# Preview candidate files first
find "$LAB/data" -type f -name '*.txt' -print

# After confirming the list, copy them to docs
find "$LAB/data" -type f -name '*.txt' -exec cp -ai '{}' "$LAB/docs/" ';'

Verification:

ls -l "$LAB/docs" | grep '\.txt' || true

Expected: docs contains the copied .txt files.

Verification and Diagnostics

Verification patterns keep you honest and prevent drift.

  • Directory exists and owned by you:
[ -d "$LAB" ] && [ -w "$LAB" ] && echo OK || echo NOT_OK
  • Copy integrity with size and checksum:
cp -a data/greek.txt docs/greek.txt
stat --format '%s' data/greek.txt docs/greek.txt
sha256sum data/greek.txt docs/greek.txt

Expected: sizes equal; checksums identical.

  • Permission change took effect:
before=$(stat -c '%A %a' bin/hello.sh)
chmod u-w bin/hello.sh
after=$(stat -c '%A %a' bin/hello.sh)
echo "before=$before after=$after"
chmod u+w bin/hello.sh

Expected: user write bit toggles between on/off.

  • Confirm what command will run:
which ls || type -a ls
command -V grep

Expected: paths to binaries or shell builtins are displayed.

  • Confirm environment assumptions:
echo "SHELL=$SHELL"
echo "UMASK=$(umask)"

Expected: values printed for auditing or runbook inclusion.

Failure Modes and Recovery

This section lists common pitfalls, how to identify them, and how to recover fast. Examples and numbers are constructed.

Failure modeSymptomQuick recovery
Overwrite by redirect (>)File content unexpectedly replacedUse backups: if you ran cp -a file{,.bak} first, mv -i file.bak file to restore. Consider set -o noclobber to prevent accidental overwrites.
Globbing expands more than intendedrm or cp affects many filesDry-run with printf '%s\n' on the glob first; switch to find ... -print to preview; use rm -i or cp -ai.
Filenames starting with dashCommands treat filename as optionUse -- to end options: rm -- -weird; or prefix path ./-weird.
Spaces or special chars in namesCommand splits wordsQuote paths: "My File.txt"; use find ... -print0 | xargs -0 for bulk ops.
Permission deniedCannot write or executeCheck ls -l, fix with chmod u+w file or chmod +x script if appropriate; confirm ownership with id and ls -ln.
Wrong directoryOperated on the wrong pathPrint pwd; restrict scope with absolute paths and -maxdepth; add set -o noclobber and -i flags for safety.
Disk fullWrites fail with No space left on deviceCheck df -h; free space or write to another filesystem; compress or delete safe-to-remove temp files.

Rollback Patterns You Can Rely On

  • Pre-change local backup for single files:
cp -a target{,.bak}
# Later, to restore
diff -u target.bak target || true
mv -i target.bak target
  • Snapshot a directory before bulk edits:
cp -a dir dir.prechange.$(date +%Y%m%d%H%M%S)
# Restore if needed (moves old copy back)
rm -rf dir && mv dir.prechange.* dir

Note: Use these inside your lab. For production data, prefer tested backup/restore procedures.

  • Reverse permission changes:
# Record before state
stat -c '%a' file > file.perms
# Change and test
chmod g-w file
# Roll back
chmod $(cat file.perms) file
  • Recover moved or misplaced files:
# Search from a known root
find "$LAB" -type f -name 'greek*' -print

Operations Checklist

Use this short checklist to run routine tasks safely and consistently.

Preparation

  • Confirm environment: uname -r; grep '^PRETTY_NAME' /etc/os-release; echo $SHELL; umask
  • Ensure space in $HOME: df -h "$HOME"
  • Set up lab: LAB="$HOME/tmp/linux-basic-commands-lab"; mkdir -p "$LAB"; cd "$LAB"
  • pwd; ls -alh; find . -maxdepth 2 -type f -print
  • head/tail/less to view content

File Operations (Use Safeguards)

  • Copy: cp -ai SRC DST
  • Move/rename: mv -i OLD NEW
  • Remove: rm -i FILE
  • Quick backup: cp -a file{,.bak}

Permissions

  • Inspect: ls -l FILE; stat -c '%A %a' FILE
  • Change (reversible): chmod u-w FILE; chmod u+w FILE

Search and Filter

  • grep -R --line-number PATTERN PATH
  • wc -l FILE; sort FILE | uniq -c | sort -nr

Process and System Status

  • ps -u "$USER" -o pid,ppid,cmd --sort=pid | head
  • df -h; du -sh "$LAB"

Archiving and Checksums

  • tar -czf snapshot.tgz .; sha256sum snapshot.tgz > snapshot.tgz.sha256
  • sha256sum -c snapshot.tgz.sha256

Verification After Changes

  • stat --format '%s' SRC DST; sha256sum SRC DST
  • grep or wc -l to confirm content expectations

Recovery

  • Use backups: mv -i file.bak file
  • Reverse perms: chmod $(cat file.perms) file
  • Find misplaced files: find "$LAB" -type f -name 'pattern'

Cleanup (When Done)

  • cd "$HOME"; rm -rf "$LAB" (confirm with pwd first)

Concise Cheat Sheet of Common Commands

The following constructed table summarizes categories, examples, and safety tips you can adapt to your own runbooks.

CategoryCommandPurposeSafety tip
Navigationpwd; ls -alhSee where you are and what is thereUse absolute paths for critical ops
Find filesfind . -maxdepth 2 -type f -printPreview target filesPreview first; apply actions second
View contenthead -n 10 file; tail -n 10 file; less fileInspect files without flooding the terminalless shows one screen; quit with q
Copy/movecp -ai SRC DST; mv -i OLD NEWPreserve and rename-i prompts to prevent accidental overwrite
Deleterm -i FILERemove files-i prompts; consider backups first
Permissionschmod u+w FILE; chmod u-w FILEGrant or remove write accessRecord previous mode to enable rollback
Search textgrep -R --line-number PATTERN PATHLocate patterns fastQuote patterns with special chars
Disk usagedf -h; du -sh DIRFilesystem and dir sizesLimit du scope to avoid long scans
Archivetar -czf out.tgz DIR; tar -tzf out.tgzSnapshot and listVerify with sha256sum before cleanup

Conclusion

You now have a safe, verifiable approach to core Linux commands, including a disposable lab layout, non-destructive defaults, and repeatable verification patterns. Keep the following habits front and center:

  • Preview with find or printf before acting.
  • Favor -i prompts and backups with cp -a file{,.bak}.
  • Prove results with stat, checksums, and line counts.
  • Record permission states before changing them.

As a next step, adapt the checklist and tables to your team runbooks. Start with a narrow, measurable pilot scenario (such as standardizing copy, move, and archive routines in home directories) that is easy to inspect locally before adopting across shared environments. This keeps risk low and builds consistent operator confidence.

Related Research

Article Quality Score

Reader usefulness 100%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL