Skip to content

Essential Linux Commands for Raspberry Pi

The Raspberry Pi runs on Linux-based operating systems, primarily Raspberry Pi OS (formerly Raspbian). Understanding essential Linux commands will help you navigate, manage files, install software, and troubleshoot your Raspberry Pi effectively. This guide covers the most important commands you'll need for daily operations.

Getting Started with the Terminal

When you first open a terminal on Raspberry Pi OS, you'll see a command prompt that looks like this:

pi@raspberrypi:~ $

This tells you:

  • pi — your username
  • raspberrypi — the hostname of your machine
  • ~ — your current directory (~ means your home directory, /home/pi)
  • $ — you're a regular user (root users see # instead)
Command Description Example
pwd Print working directory - shows your current location pwd/home/pi
ls List files and directories in current location ls
ls -l List files with detailed information (permissions, size, date) ls -l
ls -a List all files including hidden ones (starting with .) ls -a
ls -la Combine both detailed and all files options ls -la
ls -lh List with human-readable file sizes (KB, MB, GB) ls -lh
ls -lt List sorted by modification time (newest first) ls -lt
cd directory Change directory - navigate to specified location cd Documents
cd .. Move up one directory level cd ..
cd ~ Go to home directory cd ~
cd / Go to root directory cd /
cd - Go to the previous directory cd -
tree Display directory structure as a tree tree -L 2

Example workflow:

# Check where you are
pwd
# List files in current directory with details
ls -la
# Navigate to Documents folder
cd Documents
# Go back to previous directory
cd -
# Display directory tree (install with: sudo apt install tree)
tree -L 2

File Operations

Command Description Example
touch filename Create an empty file touch notes.txt
mkdir dirname Create a new directory mkdir projects
mkdir -p a/b/c Create nested directories at once mkdir -p projects/web/assets
cp source destination Copy files or directories cp file.txt backup/
cp -r source destination Copy directories recursively cp -r projects backup/
mv source destination Move/rename files or directories mv file.txt newname.txt
rm filename Remove/delete a file rm unwanted.txt
rm -r dirname Remove a directory and its contents rm -r oldproject
rm -i filename Interactive removal (asks for confirmation) rm -i important.txt
cat filename Display file contents cat config.txt
less filename View file contents with scrolling less longfile.log
head filename Show first 10 lines of file head data.csv
head -n 20 file Show first 20 lines head -n 20 data.csv
tail filename Show last 10 lines of file tail log.txt
tail -f filename Watch file for changes in real-time tail -f /var/log/syslog
wc -l filename Count lines in a file wc -l data.csv
diff file1 file2 Compare two files diff old.conf new.conf
ln -s target link Create a symbolic link ln -s /etc/nginx/sites-available/mysite mysite

Example workflow for creating a backup:

1
2
3
4
5
6
7
# Create a backup directory with timestamp
mkdir ~/backup-$(date +%Y%m%d)
# Copy important configuration files
cp /boot/firmware/config.txt ~/backup-$(date +%Y%m%d)/
cp -r ~/projects ~/backup-$(date +%Y%m%d)/
# Verify the backup was created
ls -lh ~/backup-$(date +%Y%m%d)

File Permissions

Command Description Example
chmod permissions file Change file permissions chmod 755 script.sh
chmod +x filename Make a file executable chmod +x run.sh
chmod -R 755 dir Apply permissions recursively chmod -R 755 /var/www
chown user:group file Change file owner and group sudo chown pi:pi myfile.txt
chown -R user:group dir Change ownership recursively sudo chown -R www-data:www-data /var/www

Understanding Permission Numbers

Each file has three permission groups: Owner, Group, and Others. Each group can have read (4), write (2), and execute (1) permissions:

1
2
3
4
5
rwxr-xr-x = 755
│││ │││ │││
│││ │││ ╰╯╰── Others: read(4) + execute(1) = 5
│││ ╰╯╰────── Group:  read(4) + execute(1) = 5
╰╯╰────────── Owner:  read(4) + write(2) + execute(1) = 7

Common permission patterns:

Pattern Numeric Use Case
rwxr-xr-x 755 Executable scripts, directories
rw-r--r-- 644 Regular files, config files
rw------- 600 Private files (SSH keys, passwords)
rwx------ 700 Private directories, scripts
rwxrwxr-x 775 Shared group directories

Searching and Filtering

These commands are incredibly powerful for finding files and filtering text — essential skills for any Linux user.

find — Search for Files

# Find files by name
find /home/pi -name "*.py"

# Find files modified in the last 24 hours
find /var/log -mtime -1

# Find files larger than 100MB
find / -size +100M -type f 2>/dev/null

# Find and delete all .tmp files
find ~/projects -name "*.tmp" -delete

# Find empty directories
find /home/pi -type d -empty

# Find files by permissions
find /etc -perm 777 -type f

grep — Search Inside Files

# Search for text in a file
grep "error" /var/log/syslog

# Search recursively in a directory
grep -r "GPIO" ~/projects/

# Case-insensitive search
grep -i "raspberry" README.md

# Show line numbers with results
grep -n "def " app.py

# Count matching lines
grep -c "ERROR" /var/log/syslog

# Invert match (show lines that DON'T contain the pattern)
grep -v "DEBUG" /var/log/syslog

# Search for exact word matches
grep -w "pin" config.txt

# Show 3 lines of context around each match
grep -C 3 "error" /var/log/syslog

Combining find and grep

1
2
3
4
5
# Find all Python files containing "import gpio"
find ~/projects -name "*.py" -exec grep -l "import gpio" {} \;

# Count occurrences of "TODO" across all source files
find ~/projects -name "*.cpp" -exec grep -c "TODO" {} \;

Text Processing

awk — Column-Based Processing

# Print the 1st column of a space-separated file
awk '{print $1}' data.txt

# Print processes using more than 1% CPU
ps aux | awk '$3 > 1.0 {print $11, $3"%"}'

# Sum values in a column
awk '{sum += $2} END {print "Total:", sum}' values.txt

# Print specific columns with custom formatting
df -h | awk '{printf "%-20s %s\n", $6, $5}'

sed — Stream Editor

# Replace first occurrence on each line
sed 's/old/new/' file.txt

# Replace ALL occurrences (global flag)
sed 's/old/new/g' file.txt

# Edit file in-place
sed -i 's/old/new/g' file.txt

# Delete lines containing a pattern
sed '/^#/d' config.txt    # Remove comment lines

# Insert text at a specific line
sed '5i\New line of text' file.txt

sort and uniq

# Sort file contents alphabetically
sort names.txt

# Sort numerically
sort -n numbers.txt

# Sort by the 2nd column
sort -k2 data.txt

# Remove duplicate lines (file must be sorted first)
sort data.txt | uniq

# Count occurrences of each unique line
sort access.log | uniq -c | sort -rn | head

Piping and Redirection

Piping (|) and redirection (>, >>) are what make the Linux command line truly powerful. They let you chain commands together to build complex data processing pipelines.

Redirection

# Save command output to a file (overwrite)
ls -la > filelist.txt

# Append output to a file
echo "New entry" >> log.txt

# Redirect errors to a file
command 2> errors.log

# Redirect both output and errors
command > output.log 2>&1

# Discard output
command > /dev/null 2>&1

Piping

# Count files in current directory
ls -1 | wc -l

# Find the 5 largest files in home directory
du -ah ~/ | sort -rh | head -5

# Monitor system log for SSH connections
tail -f /var/log/auth.log | grep "sshd"

# Find which processes are using the most memory
ps aux --sort=-%mem | head -10

# Extract unique IP addresses from a log file
cat /var/log/auth.log | grep -oP '\d+\.\d+\.\d+\.\d+' | sort -u

Process Management

Command Description Example
ps aux List all running processes ps aux
top Show real-time system processes top
htop Enhanced version of top (install: sudo apt install htop) htop
kill PID Terminate a process by its ID kill 1234
kill -9 PID Force kill a process kill -9 1234
killall name Kill all processes by name killall chromium
bg Resume a stopped job in the background bg
fg Bring a background job to foreground fg
jobs List background jobs jobs
nohup cmd & Run a command that survives logout nohup ./server.py &

Running Long Processes

# Run a process in the background
./long_task.sh &

# Detach a running process from the terminal
# Press Ctrl+Z to stop it, then:
bg    # Resume in background
disown  # Detach from terminal

# Better approach: use screen or tmux
sudo apt install tmux
tmux new -s mysession
# Run your command inside tmux
# Detach: Ctrl+B then D
# Reattach later:
tmux attach -t mysession

System Information

Command Description Example
uname -a Show kernel and system info uname -a
cat /etc/os-release Show OS version cat /etc/os-release
hostname -I Show IP addresses hostname -I
df -h Show disk space usage in human-readable format df -h
du -sh dir Show directory size du -sh ~/projects
free -h Display memory usage free -h
vcgencmd measure_temp Show CPU temperature vcgencmd measure_temp
vcgencmd measure_volts Show voltage vcgencmd measure_volts
vcgencmd get_throttled Check throttling status vcgencmd get_throttled
cat /proc/cpuinfo Display CPU information cat /proc/cpuinfo
lscpu Show CPU architecture details lscpu
uptime Show how long system has been running uptime
who Show who is logged in who
lsblk List block devices (disks and partitions) lsblk
lsusb List USB devices lsusb
lspci List PCI devices (Pi 5 only) lspci
dmesg \| tail Show recent kernel messages dmesg \| tail -20

Raspberry Pi-specific monitoring script:

1
2
3
4
5
6
7
8
#!/bin/bash
echo "=== Raspberry Pi System Status ==="
echo "Temperature: $(vcgencmd measure_temp)"
echo "CPU Frequency: $(vcgencmd measure_clock arm | awk -F= '{printf "%.0f MHz\n", $2/1000000}')"
echo "Memory: $(free -h | awk '/Mem:/ {print $3 "/" $2}')"
echo "Disk: $(df -h / | awk 'NR==2 {print $3 "/" $2 " (" $5 " used)"}')"
echo "Uptime: $(uptime -p)"
echo "Throttled: $(vcgencmd get_throttled)"

Save this as ~/status.sh, make it executable with chmod +x ~/status.sh, and run it anytime with ./status.sh.

Package Management

Command Description Example
sudo apt update Update package lists sudo apt update
sudo apt upgrade Upgrade all installed packages sudo apt upgrade
sudo apt full-upgrade Upgrade with dependency changes sudo apt full-upgrade
sudo apt install package Install a package sudo apt install python3-pip
sudo apt remove package Remove a package sudo apt remove unwanted-pkg
sudo apt purge package Remove package and its config files sudo apt purge unwanted-pkg
sudo apt autoremove Remove unneeded dependencies sudo apt autoremove
sudo apt clean Clear downloaded package cache sudo apt clean
dpkg -l List all installed packages dpkg -l
dpkg -l \| grep name Search installed packages dpkg -l \| grep python
apt search keyword Search for packages apt search python
apt show package Show package details apt show nginx
apt list --upgradable Show available upgrades apt list --upgradable

Example update workflow:

# Full system update (do this regularly!)
sudo apt update && sudo apt full-upgrade -y && sudo apt autoremove -y && sudo apt clean

Automatic Security Updates

Install unattended-upgrades for automatic security patches:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

Disk and Storage Management

# List all disks and partitions
lsblk

# Show disk usage summary
df -h

# Find large files in your home directory
du -ah ~ | sort -rh | head -20

# Check SD card health (read errors)
sudo dmesg | grep -i "error\|fail\|mmc"

# Mount a USB drive
sudo mkdir -p /mnt/usb
sudo mount /dev/sda1 /mnt/usb

# Unmount safely
sudo umount /mnt/usb

# Auto-mount on boot — add to /etc/fstab:
# /dev/sda1  /mnt/usb  ext4  defaults,nofail  0  2

Network Commands

Command Description Example
ip addr Show network interfaces and IP addresses ip addr
ip route Show routing table ip route
ping host Test connectivity to a host ping -c 4 google.com
traceroute host Trace route to a host traceroute google.com
nslookup domain DNS lookup nslookup google.com
dig domain Detailed DNS lookup dig google.com
ss -tuln Show listening ports (modern replacement for netstat) ss -tuln
netstat -tuln Show listening ports netstat -tuln
ssh user@host Connect to remote system via SSH ssh pi@192.168.1.5
scp file user@host:path Securely copy files between systems scp data.txt pi@192.168.1.5:~/
rsync -avz src dest Sync files efficiently rsync -avz ~/projects/ pi@backup:~/projects/
wget URL Download files from the web wget https://example.com/file.zip
curl URL Transfer data from/to servers curl -s https://api.ipify.org

Useful networking one-liners:

# Check your public IP address
curl -s https://api.ipify.org && echo

# Find all devices on your local network
sudo nmap -sn 192.168.1.0/24

# Test network speed
wget -O /dev/null http://speedtest.tele2.net/10MB.zip

# Check which process is using a port
sudo ss -tlnp | grep :80

systemd Service Management

systemd is the service manager on Raspberry Pi OS. Understanding it is essential for managing background services.

# Check service status
systemctl status ssh

# Start / stop / restart a service
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx

# Enable / disable service at boot
sudo systemctl enable ssh
sudo systemctl disable bluetooth

# View service logs
journalctl -u ssh -f         # Follow logs in real-time
journalctl -u ssh --since today  # Today's logs only
journalctl -u ssh -n 50      # Last 50 lines

# List all active services
systemctl list-units --type=service --state=running

# List failed services
systemctl --failed

For creating your own services, see Managing Your Program as a systemd Daemon.

Text Editing

While not commands per se, knowing a text editor is essential:

Editor Description How to use
nano Simple, beginner-friendly editor nano filename.txt
vim Powerful, keyboard-driven editor vim filename.txt

Basic nano commands:

  • Ctrl+O: Save file
  • Ctrl+X: Exit editor
  • Ctrl+K: Cut current line
  • Ctrl+U: Paste cut line
  • Ctrl+W: Search in file
  • Ctrl+G: Get help

Useful One-Liner Collection

Here are battle-tested one-liners that you'll use again and again on your Raspberry Pi:

# Watch CPU temperature in real-time
watch -n 1 vcgencmd measure_temp

# Find which package provides a specific command
dpkg -S $(which command_name)

# Kill all processes matching a name
pkill -f "python3 server.py"

# Create a compressed backup of a directory
tar -czf backup-$(date +%Y%m%d).tar.gz ~/projects/

# Extract a tar.gz archive
tar -xzf archive.tar.gz

# Check which files were recently modified
find /etc -mtime -7 -type f | head -20

# Generate a random password
openssl rand -base64 16

# Quick HTTP server (share files over the network)
python3 -m http.server 8000

# Monitor network bandwidth in real-time
sudo apt install nload && nload

# Clean up systemd journal logs (free disk space)
sudo journalctl --vacuum-size=100M

Shell Script Basics

Once you're comfortable with individual commands, you can combine them into scripts for automation.

Your First Script

#!/bin/bash
# my_first_script.sh — A simple Raspberry Pi maintenance script

echo "Starting maintenance..."

# Update system
sudo apt update && sudo apt upgrade -y

# Clean up
sudo apt autoremove -y
sudo apt clean

# Show status
echo ""
echo "=== System Status ==="
echo "Temperature: $(vcgencmd measure_temp)"
echo "Disk usage:"
df -h /
echo ""
echo "Maintenance complete!"

Save as ~/maintenance.sh and run:

chmod +x ~/maintenance.sh
./maintenance.sh

Key Scripting Concepts

# Variables
NAME="Raspberry Pi"
echo "Hello from $NAME"

# Conditionals
if [ -f /boot/firmware/config.txt ]; then
    echo "Config file exists"
else
    echo "Config file not found!"
fi

# Loops
for file in *.log; do
    echo "Processing $file"
    wc -l "$file"
done

# Command substitution
TEMP=$(vcgencmd measure_temp | grep -oP '\d+\.\d+')
if (( $(echo "$TEMP > 70" | bc -l) )); then
    echo "WARNING: High temperature! ${TEMP}°C"
fi

Tips for Command Line Efficiency

  1. Tab completion: Press Tab to autocomplete commands and filenames
  2. Command history:
    • Press Up Arrow to cycle through previous commands
    • history to see all past commands
    • Ctrl+R to search command history interactively
    • !! to repeat the last command (great with sudo !!)
  3. Wildcards:
    • * matches everything: rm *.tmp
    • ? matches single character: file?.txt matches file1.txt
    • [0-9] matches a range: log[0-9].txt
  4. Combining commands:
    • && — run next command only if previous succeeded: make && ./program
    • || — run next command only if previous failed: ping -c1 8.8.8.8 || echo "No internet"
    • ; — run next command regardless: echo "start"; sleep 5; echo "done"
  5. Aliases — Create shortcuts for common commands:
    1
    2
    3
    4
    # Add to ~/.bashrc
    alias ll='ls -la'
    alias temp='vcgencmd measure_temp'
    alias update='sudo apt update && sudo apt full-upgrade -y'
    
  6. Ctrl shortcuts:
    • Ctrl+C — Cancel current command
    • Ctrl+D — Exit the terminal / end input
    • Ctrl+L — Clear the screen
    • Ctrl+A — Move cursor to beginning of line
    • Ctrl+E — Move cursor to end of line
    • Ctrl+U — Delete from cursor to start of line

Learning More

  • man command — View the manual for any command
  • command --help — Show brief help information
  • tldr command — Show simplified examples (install: sudo apt install tldr)

Most importantly, don't be afraid to experiment! The command line becomes more intuitive with practice, and it's the most powerful way to control your Raspberry Pi.