Linux Command Line Basics

Linux Command Line Basics

The Linux command line is a powerful tool for managing files, programs, and system resources. This tutorial covers the essential commands every Linux user should know.

What is the Command Line?

The command line (also called terminal or shell) is a text-based interface for interacting with your computer. It allows you to run commands, manage files, and control system operations efficiently.

Basic Navigation

1. Understanding the Prompt

user@hostname:~$ 
  • user: Your username
  • hostname: Computer name
  • ~: Current directory (home directory)
  • $: Regular user prompt (# for root user)

2. Directory Navigation Commands

# Print working directory - shows where you are
pwd

# List directory contents
ls

# List with details
ls -l

# List all files (including hidden)
ls -la

# Change directory
cd /path/to/directory

# Go to home directory
cd ~

# Go to previous directory
cd -

# Go up one directory
cd ..

3. Directory Structure Examples

# Absolute paths (start from root)
cd /home/user/documents
cd /var/log
cd /usr/bin

# Relative paths (from current location)
cd documents
cd ../pictures
cd ./scripts

File Management

1. Creating Files and Directories

# Create empty files
touch newfile.txt
touch file1.txt file2.txt file3.txt

# Create directories
mkdir new_directory
mkdir project1 project2 project3

# Create nested directories
mkdir -p projects/web/frontend
mkdir -p data/2023/january

2. Copying Files and Directories

# Copy files
cp source.txt destination.txt
cp file.txt backup/file.txt

# Copy multiple files
cp *.txt backup/
cp file1.txt file2.txt file3.txt destination/

# Copy directories
cp -r source_directory destination_directory
cp -r /path/to/source /path/to/destination

3. Moving and Renaming

# Move files
mv file.txt new_location/
mv file.txt new_name.txt

# Move directories
mv old_directory new_directory

# Rename files (same as move)
mv old_name.txt new_name.txt

4. Removing Files and Directories

# Remove files
rm file.txt
rm file1.txt file2.txt

# Remove directories (must be empty)
rmdir empty_directory

# Remove directories and contents
rm -r directory_name
rm -rf directory_name  # Force remove without prompts

File Content Operations

1. Viewing File Contents

# Display entire file
cat filename.txt

# Display with line numbers
cat -n filename.txt

# View file page by page
less filename.txt
more filename.txt

# View first lines
head filename.txt
head -n 20 filename.txt  # First 20 lines

# View last lines
tail filename.txt
tail -n 10 filename.txt  # Last 10 lines

# View file in real-time (useful for logs)
tail -f logfile.txt

2. Editing Files

# Nano editor (beginner-friendly)
nano filename.txt

# Vim editor (powerful but steep learning curve)
vim filename.txt

# Emacs editor
emacs filename.txt

3. Searching Within Files

# Search for text in files
grep "search_term" filename.txt

# Search case-insensitive
grep -i "search_term" filename.txt

# Search recursively in directories
grep -r "search_term" /path/to/directory

# Show line numbers
grep -n "search_term" filename.txt

# Count occurrences
grep -c "search_term" filename.txt

File Permissions

1. Understanding Permissions

# View file permissions
ls -l

# Example output:
# -rw-r--r-- 1 user group 1024 Jan 1 12:00 file.txt
# ^^^ ^^^ ^^^
# |   |   |
# |   |   +-- Others permissions
# |   +------ Group permissions
# +---------- Owner permissions

2. Permission Types

  • r: Read (4)
  • w: Write (2)
  • x: Execute (1)

3. Changing Permissions

# Symbolic method
chmod u+x file.txt      # Add execute for owner
chmod g-w file.txt      # Remove write for group
chmod o+r file.txt      # Add read for others
chmod a+r file.txt      # Add read for all

# Numeric method
chmod 755 script.sh     # rwxr-xr-x
chmod 644 file.txt      # rw-r--r--
chmod 600 private.txt   # rw-------

# Change ownership
sudo chown user:group file.txt
sudo chown user file.txt
sudo chown :group file.txt

System Information

1. System Status

# System information
uname -a                # All system info
uname -r               # Kernel version
lsb_release -a         # Linux distribution info

# Hardware information
lscpu                  # CPU info
free -h                # Memory usage
df -h                  # Disk usage
lsblk                  # Block devices

# Process information
ps aux                 # All running processes
top                    # Interactive process viewer
htop                   # Better process viewer (if installed)

2. System Monitoring

# Resource usage
uptime                 # System uptime and load
iostat                 # I/O statistics
vmstat                 # Virtual memory statistics

# Network information
ip addr                # IP addresses
netstat -tuln          # Network connections
ss -tuln               # Socket statistics (modern)

Package Management

1. apt (Debian/Ubuntu)

# Update package lists
sudo apt update

# Upgrade packages
sudo apt upgrade

# Install packages
sudo apt install package_name
sudo apt install vim git curl

# Remove packages
sudo apt remove package_name
sudo apt purge package_name  # Remove with config files

# Search for packages
apt search keyword

# Show package information
apt show package_name

2. yum/dnf (Red Hat/CentOS/Fedora)

# Update package lists
sudo dnf update

# Install packages
sudo dnf install package_name

# Remove packages
sudo dnf remove package_name

# Search for packages
sudo dnf search keyword

3. pacman (Arch Linux)

# Update system
sudo pacman -Syu

# Install packages
sudo pacman -S package_name

# Remove packages
sudo pacman -R package_name

# Search for packages
pacman -Ss keyword

Process Management

1. Managing Processes

# List processes
ps aux
ps -ef

# Find specific process
ps aux | grep firefox

# Kill processes
kill PID
kill -9 PID  # Force kill

# Kill by name
pkill firefox
killall firefox

# Run processes in background
command &

# Bring background process to foreground
fg

# List background jobs
jobs

2. System Services

# Systemd (modern Linux)
sudo systemctl status service_name
sudo systemctl start service_name
sudo systemctl stop service_name
sudo systemctl restart service_name
sudo systemctl enable service_name  # Start on boot
sudo systemctl disable service_name

# Service examples
sudo systemctl status nginx
sudo systemctl restart sshd

Network Commands

1. Basic Network Operations

# Test connectivity
ping google.com
ping 8.8.8.8

# Download files
wget https://example.com/file.zip
curl -O https://example.com/file.zip

# Network configuration
ip addr show
ip route show

# DNS lookup
nslookup google.com
dig google.com

# Network connections
netstat -tuln
ss -tuln

2. SSH and Remote Access

# Connect to remote server
ssh user@hostname
ssh -p 2222 user@hostname  # Different port

# Copy files remotely
scp file.txt user@hostname:/path/to/destination/
scp -r directory user@hostname:/path/to/destination/

# Secure copy with options
scp -P 2222 file.txt user@hostname:~/file.txt

Text Processing

1. Filtering and Transforming Text

# Sort lines
sort filename.txt
sort -r filename.txt  # Reverse sort
sort -n filename.txt  # Numeric sort

# Remove duplicate lines
sort filename.txt | uniq
uniq filename.txt

# Count lines, words, characters
wc filename.txt
wc -l filename.txt  # Lines only
wc -w filename.txt  # Words only
wc -c filename.txt  # Characters only

# Extract columns
cut -d',' -f1,3 filename.txt  # Fields 1 and 3, comma delimiter
cut -d' ' -f2 filename.txt    # Field 2, space delimiter

2. Advanced Text Processing

# Find and replace text
sed 's/old_text/new_text/g' filename.txt

# Delete lines containing pattern
sed '/pattern/d' filename.txt

# Print specific lines
sed -n '10,20p' filename.txt  # Lines 10-20

# AWK for complex text processing
awk '{print $1}' filename.txt  # Print first column
awk -F',' '{print $2}' filename.txt  # Second column, comma delimiter

Shell Scripting Basics

1. Creating Simple Scripts

#!/bin/bash

# This is a comment
echo "Hello, World!"

# Variables
NAME="John"
echo "Hello, $NAME!"

# Command substitution
CURRENT_DATE=$(date)
echo "Today is: $CURRENT_DATE"

# Conditional statement
if [ "$NAME" = "John" ]; then
    echo "Welcome, John!"
else
    echo "Welcome, guest!"
fi

2. Making Scripts Executable

# Create script file
nano myscript.sh

# Make executable
chmod +x myscript.sh

# Run script
./myscript.sh

Useful Tips and Tricks

1. Command History

# View command history
history

# Search command history
Ctrl + r  # Then type to search

# Run previous command
!!

# Run command with sudo
sudo !!

# Run nth command from history
!50

2. Tab Completion

# Use Tab key to autocomplete
cd /ho[Tab]  # Becomes cd /home
ls file[Tab] # Shows matching files

3. Command Aliases

# Create temporary alias
alias ll='ls -la'
alias la='ls -A'
alias grep='grep --color=auto'

# Make aliases permanent (add to ~/.bashrc)
echo "alias ll='ls -la'" >> ~/.bashrc
source ~/.bashrc

4. Pipes and Redirection

# Pipe output to another command
ls -la | grep ".txt"
ps aux | grep firefox

# Redirect output to file
ls -la > file_list.txt
echo "Hello" >> logfile.txt  # Append

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

Safety and Best Practices

1. Important Safety Tips

# Always be careful with rm -rf
# Double-check before running destructive commands

# Use interactive mode for dangerous operations
rm -i filename.txt  # Ask before removing
cp -i source.txt dest.txt  # Ask before overwriting

# Test commands with echo first
echo rm *.txt  # See what would be deleted

2. Backup Strategies

# Create backups before major changes
cp important.txt important.txt.backup

# Use rsync for backups
rsync -av source/ backup/

# Create compressed backups
tar -czf backup.tar.gz directory/

Getting Help

1. Built-in Help

# Manual pages
man command_name
man ls
man grep

# Help flag
command --help
ls --help
grep --help

# Info pages (more detailed)
info command_name

2. Finding Commands

# Find command location
which ls
whereis python

# Search for commands
apropos keyword
man -k keyword

External Resources:

Related Tutorials:

Last updated on