Basic_commands
Chapter 5: Basic Linux Commands and Navigation
Section titled “Chapter 5: Basic Linux Commands and Navigation”Overview
Section titled “Overview”This chapter covers essential Linux commands for navigation, file operations, text processing, and system administration. These commands form the foundation that every Linux sysadmin must master.
5.1 File System Navigation
Section titled “5.1 File System Navigation”Navigation Commands
Section titled “Navigation Commands”| Command | Description | Example |
|---|---|---|
pwd | Print working directory | pwd |
cd | Change directory | cd /etc |
ls | List directory contents | ls -la |
tree | Display directory tree | tree -L 2 |
cd Command Shortcuts
Section titled “cd Command Shortcuts”cd / # Go to rootcd ~ # Go to homecd - # Go to previous directorycd .. # Go to parent directorycd ../.. # Go up two levelsls Command Options
Section titled “ls Command Options”ls -lah # All files, long format, human readablels -lSr # Long, by size, reverse (smallest first)ls -lt # Long, sorted by time (newest first)ls -ld /dir # Show directory info, not contentsls -i # Show inode numbersls -R # Recursive listing5.2 File Operations
Section titled “5.2 File Operations”Creating Files and Directories
Section titled “Creating Files and Directories”# Create empty filetouch filename.txt
# Create multiple empty filestouch file1.txt file2.txt file3.txt
# Create directorymkdir dirname
# Create nested directoriesmkdir -p /path/to/nested/dir
# Create directory with specific permissionsmkdir -m 755 dirnameCopying, Moving, Deleting
Section titled “Copying, Moving, Deleting”# Copy filecp source.txt destination.txt
# Copy with preserve attributescp -p source.txt destination.txt
# Copy directory recursivelycp -r /source/dir /destination/
# Copy with archive mode (preserves everything)cp -a /source/dir /destination/
# Move/Renamemv oldname.txt newname.txtmv file.txt /other/directory/
# Delete filerm filename.txt
# Force delete without promptrm -f filename.txt
# Delete directory and contentsrm -rf dirname
# Delete empty directoryrmdir dirnameFile Archiving
Section titled “File Archiving”# Create tar archivetar -cvf archive.tar /path/to/dir
# Create compressed tartar -czvf archive.tar.gz /path/to/dirtar -cjvf archive.tar.bz2 /path/to/dirtar -cJvf archive.tar.xz /path/to/dir
# Extract tartar -xvf archive.tartar -xzvf archive.tar.gztar -xjvf archive.tar.bz2tar -xJvf archive.tar.xz
# List contentstar -tvf archive.tar5.3 Viewing File Contents
Section titled “5.3 Viewing File Contents”cat, less, more
Section titled “cat, less, more”cat file.txt # View entire filecat -n file.txt # With line numberscat -b file.txt # Number non-empty linestac file.txt # View file in reverse
less file.txt # Paginated viewing (better than more)# Less commands: /search, n(next), N(previous), q(quit), g(start), G(end)
more file.txt # Scroll forward only (legacy)head and tail
Section titled “head and tail”head -n 20 file.txt # First 20 lineshead -c 100 file.txt # First 100 bytestail -n 20 file.txt # Last 20 linestail -f file.txt # Follow file (live updates)tail -f -n 100 file.txt # Follow with 100 lines buffertail -F file.txt # Follow even if file rotated5.4 Text Processing
Section titled “5.4 Text Processing”grep - Search in Files
Section titled “grep - Search in Files”# Basic searchgrep "pattern" file.txtgrep -i "pattern" file.txt # Case insensitivegrep -r "pattern" /dir/ # Recursive searchgrep -n "pattern" file.txt # Show line numbersgrep -v "pattern" file.txt # Invert match (show non-matching)grep -c "pattern" file.txt # Count matches
# Extended grep (regex)grep -E "pattern1|pattern2" file.txtegrep "pattern1|pattern2" file.txt
# Fixed string (no regex)grep -F "literal.text" file.txtfgrep "literal.text" file.txt
# Context optionsgrep -A 3 "pattern" file.txt # Show 3 lines after matchgrep -B 3 "pattern" file.txt # Show 3 lines beforegrep -C 3 "pattern" file.txt # Show 3 lines around
# Useful examplesps aux | grep nginx # Find nginx processgrep -r --include="*.log" "ERROR" /var/log/ls /usr/bin | grep ^l # Commands starting with 'l'sed - Stream Editor
Section titled “sed - Stream Editor”# Replace first occurrence in each linesed 's/old/new/' file.txt
# Replace all occurrencessed 's/old/new/g' file.txt
# In-place editsed -i 's/old/new/g' file.txt
# Replace on specific linesed -i '5s/old/new/' file.txt
# Delete lines matching patternsed '/pattern/d' file.txt
# Print specific linessed -n '5,10p' file.txt # Print lines 5-10sed -n '5p' file.txt # Print line 5
# Multiple commandssed -e 's/old1/new1/' -e 's/old2/new2/' file.txtawk - Text Processing
Section titled “awk - Text Processing”# Print first columnawk '{print $1}' file.txt
# Print specific columnsawk '{print $1, $3}' file.txt
# Use custom delimiterawk -F',' '{print $1}' file.csv
# Print lines where column matchesawk '$3 > 100' file.txt
# Built-in variablesawk 'BEGIN {FS=","} {print $1}' file.txt # Field separatorawk 'BEGIN {OFS=" - "} {print $1, $2}' # Output field separatorawk '{print NR, $0}' file.txt # NR = line number
# Conditional processingawk '{if ($3 > 50) print $1, $3}' file.txt
# Summing valuesawk '{sum += $3} END {print sum}' file.txt5.5 System Information Commands
Section titled “5.5 System Information Commands”System Overview
Section titled “System Overview”uname -a # All system infouname -r # Kernel releaseuname -m # Machine hardware nameuname -n # Network node hostnamehostname # Hostnamehostname -I # IP addresseswhoami # Current userdate # Current date/timedate +%Y-%m-%d # Formatted dateuptime # System uptimeHardware Information
Section titled “Hardware Information”# CPUlscpu # CPU architecture detailscat /proc/cpuinfo # Detailed CPU info
# Memoryfree -h # Memory and swap usagefree -m # Memory in MBcat /proc/meminfo # Detailed memory info
# Diskdf -h # Disk space usage (human readable)df -i # Inode usagedu -sh /dir # Directory sizedu -h --max-depth=1 # Size of subdirectories
# Block deviceslsblk # Block devices treeblkid # UUIDs and typesfdisk -l # Partition table
# PCI/USBlspci # PCI deviceslsusb # USB deviceslshw # Hardware info (comprehensive)Process Information
Section titled “Process Information”ps aux # All processesps aux | head -20 # Top 20 processesps -ef # Full formatps -eo pid,ppid,cmd,%mem,%cpu # Custom columnspidof nginx # PID of processpgrep nginx # Find processes by name
# Real-time monitoringtop # Process monitor (legacy)htop # Enhanced process viewer (recommended)btop # Modern, GPU-acceleratedatop # Advanced system monitor
# Kill processeskill PID # Graceful killkill -9 PID # Force killpkill nginx # Kill by namekillall nginx # Kill all with name5.6 Pipes and Redirection
Section titled “5.6 Pipes and Redirection”File Descriptors
Section titled “File Descriptors”| Descriptor | Name | Description |
|---|---|---|
| 0 | stdin | Standard input |
| 1 | stdout | Standard output |
| 2 | stderr | Standard error |
Redirection Examples
Section titled “Redirection Examples”command > output.txt # Overwrite stdout to filecommand >> output.txt # Append stdout to filecommand 2> error.txt # Redirect stderr onlycommand 2>&1 # Redirect stderr to stdoutcommand &> all.txt # Redirect both to same filecommand 1>out.txt 2>err.txt # Separate files
# Discard outputcommand > /dev/null 2>&1command &>/dev/null
# Read from filecommand < input.txtcommand << EOFheredoc contentEOFPipe Examples
Section titled “Pipe Examples”ls -la | grep txt # List and searchcat file | sort | uniq # Sort and remove duplicatesps aux | grep nginx # Find nginx processdf -h | grep -v tmpfs # Exclude virtual filesystemstail -f log | grep ERROR # Real-time error filteringcat file | wc -l # Count linesAdvanced Piping
Section titled “Advanced Piping”# Tee - split output to file and terminalcommand | tee output.txt
# Pipe to rootecho "content" | sudo tee /etc/file
# xargs - build commands from inputfind . -name "*.log" | xargs rmls | xargs -I {} echo "File: {}"
# Process substitutiondiff <(cmd1) <(cmd2) # Compare command outputswhile read line; do echo $line; done < file.txt5.7 Finding Files
Section titled “5.7 Finding Files”find Command
Section titled “find Command”# Basic findfind /path -name "filename"find /path -name "*.log"
# Case insensitivefind /path -iname "filename"
# By typefind /path -type f # Regular filesfind /path -type d # Directoriesfind /path -type l # Symbolic links
# By timefind /path -mtime -7 # Modified in last 7 daysfind /path -atime +30 # Accessed more than 30 days agofind /path -ctime -1 # Changed in last day
# By sizefind /path -size +100M # Larger than 100MBfind /path -size -1G # Smaller than 1GB
# By permissionsfind /path -perm 644 # Exact permissionsfind /path -perm -u+x # Execute bit set
# Execute commands on resultsfind /path -name "*.log" -exec rm {} \;find /path -name "*.log" -delete
# Combining conditionsfind /path -name "*.txt" -and -size +1Mfind /path \( -name "*.log" -o -name "*.tmp" \)locate Command
Section titled “locate Command”# Install mlocate firstsudo pacman -S mlocatesudo updatedb
# Quick search (uses database)locate filenamelocate -i filename # Case insensitive
# Show only existing fileslocate -e filenamewhich and whereis
Section titled “which and whereis”which python # Path to executablewhereis python # Binary, source, man pagestype -a bash # All locations of command5.8 Arch Linux Specific Commands
Section titled “5.8 Arch Linux Specific Commands”Pacman Package Manager
Section titled “Pacman Package Manager”# Sync and updatesudo pacman -Syu # Full system upgradesudo pacman -Sy # Sync database only
# Install/Removesudo pacman -S package_namesudo pacman -R package_namesudo pacman -Rs package_name # Remove with dependencies
# Searchpacman -Ss keyword # Search packagespacman -Qs keyword # Search installedpacman -Qi package_name # Package infopacman -Ql package_name # List files
# Clean cachesudo pacman -Scc # Clean cache completelysudo pacman -Sc # Remove old packagesAUR Helper (yay)
Section titled “AUR Helper (yay)”yay -S package_name # Install from AURyay -Ss keyword # Search AURyay -Yc # Clean unused depsyay -Ytd # Remove unneeded dependenciesyay -Syu --devel # Update including AURSystemd Service Management
Section titled “Systemd Service Management”# Service controlsudo systemctl start servicesudo systemctl stop servicesudo systemctl restart servicesudo systemctl reload service
# Enable/Disable at bootsudo systemctl enable servicesudo systemctl disable service
# Statussystemctl status servicesystemctl is-enabled servicesystemctl is-active service
# List servicessystemctl list-units --type=servicesystemctl list-unit-files5.9 Text Editors
Section titled “5.9 Text Editors”Vim Basics
Section titled “Vim Basics”# Modes: Normal (default), Insert (i), Command (:), Visual (v)
# Navigationh j k l # Left, down, up, rightw / b # Word forward/back0 / $ # Line start/endgg / G # File start/end:123 # Go to line 123
# Editingi # Insert modea # Append after cursoro / O # New line below/abovedd # Delete linedw # Delete wordyy # Yank (copy) linep # Pasteu # UndoCtrl+r # Redo
# Search and replace:/pattern # Search forward:?pattern # Search backward:%s/old/new/g # Replace all:%s/old/new/gc # Replace with confirmation
# Save and quit:w # Save:q # Quit:wq / :x # Save and quit:q! # Quit without savingNano Basics
Section titled “Nano Basics”# Simple editor for beginnersnano file.txt
# Shortcuts shown at bottom (^ = Ctrl)^O # Save (WriteOut)^X # Exit^W # Where is (search)^K # Cut line^U # Uncut (paste)^C # Show cursor position5.10 Practice Exercises
Section titled “5.10 Practice Exercises”Hands-On Tasks
Section titled “Hands-On Tasks”# Exercise 1: Navigationcd / && ls -lacd /var/log && pwdcd ~ && cd -
# Exercise 2: File operationstouch test.txtcp test.txt test_copy.txtmv test_copy.txt test_new.txtrm test_new.txt
# Exercise 3: Find and delete old filesfind /tmp -type f -mtime +7 -delete
# Exercise 4: System infouname -rfree -hdf -h
# Exercise 5: Process monitoringps aux --sort=-%cpu | head -5ps aux --sort=-%mem | head -5
# Exercise 6: Log analysistail -n 100 /var/log/pacman.log | grep -i error
# Exercise 7: Text processingcat /etc/passwd | awk -F: '{print $1, $7}'Summary
Section titled “Summary”In this chapter, you learned:
- ✅ File system navigation (cd, ls, pwd, tree)
- ✅ File operations (touch, cp, mv, rm, mkdir, tar)
- ✅ Viewing file contents (cat, less, head, tail)
- ✅ Text processing (grep, sed, awk)
- ✅ System information commands
- ✅ Pipes and redirection
- ✅ Finding files (find, locate)
- ✅ Arch Linux specific commands (pacman, yay)
- ✅ Basic text editors (vim, nano)
Next Chapter
Section titled “Next Chapter”Chapter 6: User Management Commands
Last Updated: February 2026