普通视图

发现新文章,点击刷新页面。
昨天 — 2026年2月16日Linux Tips, Tricks and Tutorials on Linuxize

Best Linux Distributions for Every Use Case

A Linux distribution (or “distro”) is an operating system built on the Linux kernel, combined with GNU tools, libraries, and software packages. Each distro includes a desktop environment, package manager, and preinstalled applications tailored to specific use cases.

With hundreds of Linux distributions available, choosing the right one can be overwhelming. This guide covers the best Linux distributions for different types of users, from complete beginners to security professionals.

How to Choose a Linux Distro

When selecting a Linux distribution, consider these factors:

  • Experience level — Some distros are beginner-friendly, while others require technical knowledge
  • Hardware — Older computers benefit from lightweight distros like Xubuntu and other Xfce-based systems
  • Purpose — Desktop use, gaming, server deployment, or security testing all have ideal distros
  • Software availability — Check if your required applications are available in the distro’s repositories
  • Community support — Larger communities mean more documentation and help

Linux Distros for Beginners

These distributions are designed with user-friendliness in mind, featuring intuitive interfaces and easy installation.

Ubuntu

Ubuntu is the most popular Linux distribution and an excellent starting point for newcomers. Developed by Canonical, it offers a polished desktop experience with the GNOME environment and extensive hardware support.

Ubuntu desktop screenshot

Ubuntu comes in several editions:

  • Ubuntu Desktop — Standard desktop with GNOME
  • Ubuntu Server — For server deployments
  • Kubuntu, Lubuntu, Xubuntu — Alternative desktop environments

Ubuntu releases new versions every six months, with Long Term Support (LTS) versions every two years receiving five years of security updates.

Website: https://ubuntu.com/

Linux Mint

Linux Mint is an excellent choice for users coming from Windows. Its Cinnamon desktop environment provides a familiar layout with a taskbar, start menu, and system tray.

Linux Mint desktop screenshot

Key features:

  • Comes with multimedia codecs preinstalled
  • LibreOffice productivity suite included
  • Update Manager for easy system maintenance
  • Available with Cinnamon, MATE, or Xfce desktops

Website: https://linuxmint.com/

Pop!_OS

Developed by System76, Pop!_OS is based on Ubuntu but optimized for productivity and gaming. It ships with the COSMIC desktop environment (built in Rust by System76), featuring built-in window tiling, a launcher for quick app access, and excellent NVIDIA driver support out of the box.

Pop!_OS desktop screenshot

Pop!_OS is particularly popular among:

  • Gamers (thanks to Steam and Proton integration)
  • Developers (includes many development tools)
  • Users with NVIDIA graphics cards

Website: https://pop.system76.com/

Zorin OS

Zorin OS is a beginner-focused distribution designed to make the move from Windows or macOS easier. It includes polished desktop layouts, strong hardware compatibility, and a simple settings experience for new users.

Zorin OS is a strong option when you want:

  • A familiar desktop layout with minimal setup
  • Stable Ubuntu-based package compatibility
  • Good out-of-the-box support for everyday desktop tasks
Zorin OS desktop screenshot

Website: https://zorin.com/os/

elementary OS

elementary OS is a design-focused distribution with a macOS-like interface called Pantheon. It emphasizes simplicity, consistency, and a curated app experience through its AppCenter.

elementary OS desktop screenshot

elementary OS is a good fit when you want:

  • A clean, visually polished desktop out of the box
  • A curated app store with native applications
  • A macOS-like workflow on Linux

Website: https://elementary.io/

Lightweight Linux Distros

These distributions are designed for older hardware or users who prefer a minimal, fast system.

Xubuntu

Xubuntu combines Ubuntu’s reliability with the Xfce desktop environment, offering a good balance between performance and features. It is lighter than standard Ubuntu while remaining full-featured for daily desktop use.

Xubuntu is a practical choice when you need:

  • Better performance on older hardware
  • A traditional desktop workflow
  • Ubuntu repositories and long-term support options
Xubuntu desktop screenshot

Website: https://xubuntu.org/

Lubuntu

Lubuntu uses the LXQt desktop environment, making it one of the lightest Ubuntu-based distributions available. It is designed for very old or resource-constrained hardware where even Xfce feels heavy.

Lubuntu desktop screenshot

Lubuntu works well when you need:

  • Minimal memory and CPU usage
  • A functional desktop on very old hardware
  • Access to Ubuntu repositories and LTS support

Website: https://lubuntu.me/

Linux Distros for Advanced Users

These distributions offer more control and customization but require technical knowledge to set up and maintain.

Arch Linux

Arch Linux follows a “do-it-yourself” philosophy, providing a minimal base system that users build according to their needs. It uses a rolling release model, meaning you always have the latest software without major version upgrades.

Key features:

  • Pacman package manager with access to vast repositories
  • Arch User Repository (AUR) for community packages
  • Excellent documentation in the Arch Wiki
  • Complete control over every aspect of the system
Arch Linux desktop screenshot
Tip
Arch Linux requires manual installation via the command line. If you want the Arch experience with an easier setup, consider Manjaro or EndeavourOS.

Website: https://archlinux.org/

EndeavourOS

EndeavourOS is an Arch-based distribution that keeps the Arch philosophy while simplifying installation and initial setup. It is popular among users who want a near-Arch experience without doing a fully manual install.

EndeavourOS gives you:

  • Rolling release updates
  • Access to Arch repositories and AUR packages
  • A cleaner onboarding path than a base Arch install
EndeavourOS desktop screenshot

Website: https://endeavouros.com/

Fedora

Fedora is a cutting-edge distribution sponsored by Red Hat. It showcases the latest open-source technologies while maintaining stability, making it popular among developers and system administrators.

Fedora desktop screenshot

Fedora editions include:

  • Fedora Workstation — Desktop with GNOME
  • Fedora Server — For server deployments
  • Fedora Silverblue — Immutable desktop OS
  • Fedora Spins — Alternative desktops (KDE, Xfce, etc.)

Many Red Hat technologies debut in Fedora before reaching RHEL, making it ideal for learning enterprise Linux.

Website: https://fedoraproject.org/

openSUSE

openSUSE is a community-driven distribution known for its stability and powerful administration tools. It offers two main variants:

  • openSUSE Leap — Regular releases based on SUSE Linux Enterprise
  • openSUSE Tumbleweed — Rolling release with the latest packages

The YaST (Yet another Setup Tool) configuration utility makes system administration straightforward, handling everything from software installation to network configuration.

openSUSE desktop screenshot

Website: https://www.opensuse.org/

Linux Distros for Gaming

Gaming-focused distributions prioritize current graphics stacks, controller support, and compatibility with modern Steam and Proton workflows.

Bazzite

Bazzite is an immutable Fedora-based desktop optimized for gaming and handheld devices. It ships with gaming-focused defaults and integrates well with Steam, Proton, and modern GPU drivers.

Bazzite is ideal when you want:

  • A Steam-first gaming setup
  • Reliable rollback and update behavior from an immutable base
  • A distro tuned for gaming PCs and handheld hardware
Bazzite desktop screenshot

Website: https://bazzite.gg/

Linux Distros for Servers

These distributions are optimized for stability, security, and long-term support in server environments.

Debian

Debian is one of the oldest and most influential Linux distributions. Known for its rock-solid stability and rigorous testing process, it serves as the foundation for Ubuntu, Linux Mint, Kali Linux, and many other distributions.

Debian desktop screenshot

Debian offers three release channels:

  • Stable — Thoroughly tested, ideal for production servers
  • Testing — Upcoming stable release with newer packages
  • Unstable (Sid) — Rolling release with the latest software

With over 59,000 packages in its repositories, Debian supports more hardware architectures than any other Linux distribution.

Website: https://www.debian.org/

Red Hat Enterprise Linux (RHEL)

RHEL is the industry standard for enterprise Linux deployments. It offers:

  • 10-year support lifecycle
  • Certified hardware and software compatibility
  • Red Hat Insights for predictive analytics
  • Professional support from Red Hat

RHEL runs on multiple architectures including x86_64, ARM64, IBM Power, and IBM Z.

Website: https://www.redhat.com/

Rocky Linux

After CentOS shifted to CentOS Stream, Rocky Linux emerged as a community-driven RHEL-compatible distribution. Founded by one of the original CentOS creators, it provides 1:1 binary compatibility with RHEL.

Rocky Linux desktop screenshot

Rocky Linux is ideal for:

  • Organizations previously using CentOS
  • Production servers requiring stability
  • Anyone needing RHEL compatibility without the cost

Website: https://rockylinux.org/

Ubuntu Server

Ubuntu Server is widely used for cloud deployments and containerized workloads. It powers a significant portion of public cloud instances on AWS, Google Cloud, and Azure.

Features include:

  • Regular and LTS releases
  • Excellent container and Kubernetes support
  • Ubuntu Pro for extended security maintenance
  • Snap packages for easy application deployment

Website: https://ubuntu.com/server

SUSE Linux Enterprise Server (SLES)

SUSE Linux Enterprise Server is designed for mission-critical workloads. It excels in:

  • SAP HANA deployments
  • High-performance computing
  • Mainframe environments
  • Edge computing

SLES offers a common codebase across different environments, simplifying workload migration.

Website: https://www.suse.com/products/server/

Linux Distros for Security and Privacy

These distributions focus on security testing, anonymity, and privacy protection.

Kali Linux

Kali Linux is the industry-standard platform for penetration testing and security research. Maintained by Offensive Security, it includes hundreds of security tools preinstalled.

Common use cases:

  • Penetration testing
  • Security auditing
  • Digital forensics
  • Reverse engineering
Kali Linux desktop screenshot
Warning
Kali Linux is designed for security professionals. It should not be used as a daily driver operating system.

Website: https://www.kali.org/

Tails

Tails (The Amnesic Incognito Live System) is a portable operating system designed for privacy and anonymity. It runs from a USB drive and routes all traffic through the Tor network.

Key features:

  • Leaves no trace on the host computer
  • All connections go through Tor
  • Built-in encryption tools
  • Amnesic by design (forgets everything on shutdown)
Tails desktop screenshot

Website: https://tails.net/

Qubes OS

Qubes OS takes a unique approach to security by isolating different activities in separate virtual machines called “qubes.” If one qube is compromised, others remain protected.

The Xen hypervisor runs directly on hardware, providing strong isolation between:

  • Work applications
  • Personal browsing
  • Untrusted software
  • Sensitive data

Website: https://www.qubes-os.org/

Parrot Security OS

Parrot Security is a Debian-based distribution for security testing, development, and privacy. It is lighter than Kali Linux and can serve as a daily driver.

Parrot offers several editions:

  • Security Edition — Full security toolkit
  • Home Edition — Privacy-focused daily use
  • Cloud Edition — For cloud deployments

Website: https://parrotsec.org/

Getting Started

Once you have chosen a distro, the next steps are:

  1. Download the ISO from the official website
  2. Create a bootable USB drive — See our guide on creating a bootable Linux USB
  3. Try it live before installing (most distros support this)
  4. Install following the distro’s installation wizard

Quick Comparison

Distro Best For Desktop Package Manager Based On
Ubuntu Beginners GNOME APT Debian
Linux Mint Windows users Cinnamon APT Ubuntu
Zorin OS New Linux users GNOME (Zorin desktop) APT Ubuntu
elementary OS macOS-like experience Pantheon APT Ubuntu
Fedora Developers GNOME DNF Independent
Debian Stability/Servers GNOME APT Independent
Arch Linux Advanced users Any Pacman Independent
EndeavourOS Arch with easier setup Xfce (default) Pacman Arch Linux
Pop!_OS Gaming/Developers COSMIC APT Ubuntu
Bazzite Gaming KDE/GNOME variants RPM-OSTree Fedora
Rocky Linux Enterprise servers None DNF RHEL
Xubuntu Older hardware Xfce APT Ubuntu
Lubuntu Very old hardware LXQt APT Ubuntu
Kali Linux Security testing Xfce APT Debian

FAQ

Which Linux distro is best for beginners?
Ubuntu, Linux Mint, and Zorin OS are the best choices for beginners. Ubuntu has the largest community and most documentation, while Linux Mint and Zorin OS provide a familiar desktop experience.

Can I try a Linux distro without installing it?
Yes. Most distributions support “live booting” from a USB drive, allowing you to test the system without making any changes to your computer.

Is Linux free?
Most Linux distributions are completely free to download and use. Some enterprise distros like RHEL offer paid support subscriptions.

Can I run Windows software on Linux?
Many Windows applications run on Linux through Wine or Proton (for games via Steam). Native alternatives like LibreOffice, GIMP, and Firefox are also available.

What is a rolling release distro?
A rolling release distro (like Arch Linux or openSUSE Tumbleweed) delivers continuous updates instead of major version upgrades. You always have the latest software, but updates require more attention.

Conclusion

The best Linux distribution depends entirely on your needs and experience level. If you are new to Linux, start with Ubuntu, Linux Mint, or Zorin OS. If you want full control over your system, try Arch Linux, EndeavourOS, or Fedora. For gaming, Pop!_OS and Bazzite are strong options. For servers, Debian, Rocky Linux, Ubuntu Server, and RHEL are all solid choices. For security testing, Kali Linux and Parrot Security are the industry standards.

Most distributions are free to download and try. Create a bootable USB, test a few options, and find the one that fits your workflow.

If you have any questions, feel free to leave a comment below.

SCP Cheatsheet

Basic Syntax

Use this general form for scp commands.

Command Description
scp SOURCE DEST General scp syntax
scp file.txt user@host:/path/ Copy local file to remote
scp user@host:/path/file.txt . Copy remote file to current directory
scp user@host:/path/file.txt /local/path/ Copy remote file to local directory

Upload Files

Copy local files to a remote host.

Command Description
scp file.txt user@host:/tmp/ Upload one file
scp file1 file2 user@host:/tmp/ Upload multiple files
scp *.log user@host:/var/log/archive/ Upload matching files
scp -p file.txt user@host:/tmp/ Preserve modification times and mode

Download Files

Copy files from a remote host to your local system.

Command Description
scp user@host:/tmp/file.txt . Download to current directory
scp user@host:/tmp/file.txt ~/Downloads/ Download to specific directory
scp user@host:'/var/log/*.log' . Download remote wildcard (quoted)
scp user@host:/tmp/file.txt ./new-name.txt Download and rename locally

Copy Directories

Use -r for recursive directory transfers.

Command Description
scp -r dir/ user@host:/tmp/ Upload directory recursively
scp -r user@host:/var/www/ ./backup/ Download directory recursively
scp -r dir1 dir2 user@host:/tmp/ Upload multiple directories
scp -rp project/ user@host:/srv/ Recursive copy and preserve attributes

Ports, Keys, and Identity

Connect with custom SSH settings.

Command Description
scp -P 2222 file.txt user@host:/tmp/ Use custom SSH port
scp -i ~/.ssh/id_ed25519 file.txt user@host:/tmp/ Use specific private key
scp -o IdentityFile=~/.ssh/id_ed25519 file.txt user@host:/tmp/ Set key with -o option
scp -o StrictHostKeyChecking=yes file.txt user@host:/tmp/ Enforce host key verification

Performance and Reliability

Tune speed, verbosity, and resilience.

Command Description
scp -C large-file.iso user@host:/tmp/ Enable compression
scp -l 8000 file.txt user@host:/tmp/ Limit bandwidth (Kbit/s)
scp -v file.txt user@host:/tmp/ Verbose output for debugging
scp -q file.txt user@host:/tmp/ Quiet mode
scp -o ConnectTimeout=10 file.txt user@host:/tmp/ Set connection timeout

Remote to Remote Copy

Transfer files between two remote hosts.

Command Description
scp user1@host1:/path/file user2@host2:/path/ Copy between remote hosts
scp -3 user1@host1:/path/file user2@host2:/path/ Route transfer through local host
scp -P 2222 user1@host1:/path/file user2@host2:/path/ Use custom port (applies to both hosts)

Common Patterns

Frequently used command combinations.

Command Description
scp -r ./site user@host:/var/www/ Deploy static site files
scp -i ~/.ssh/id_ed25519 -P 2222 backup.sql user@host:/tmp/ Upload with key and custom port
scp user@host:/etc/nginx/nginx.conf ./ Pull config for review
scp -rp ./configs user@host:/etc/myapp/ Copy configs and keep metadata

Troubleshooting

Check Command
Permission denied Verify user has write access to the destination path
Host key verification failed ssh-keygen -R hostname to remove old key, then retry
Connection refused on custom port scp -P PORT file user@host:/path/ (uppercase -P)
Transfer stalls or times out scp -o ConnectTimeout=10 -o ServerAliveInterval=15 file user@host:/path/
Not a regular file error Add -r for directories: scp -r dir/ user@host:/path/
Protocol error on OpenSSH 9.0+ scp -O file user@host:/path/ to use legacy SCP protocol
Debug connection issues scp -v file user@host:/path/ for verbose SSH output

Related Guides

Use these articles for detailed file transfer and SSH workflows.

Guide Description
How to Use SCP Command to Securely Transfer Files Full scp guide with practical examples
SSH Command in Linux SSH options, authentication, and connection examples
How to Use Linux SFTP Command to Transfer Files Interactive secure file transfer over SSH
How to Use Rsync for Local and Remote Data Transfer Incremental sync and directory transfer
昨天以前Linux Tips, Tricks and Tutorials on Linuxize

Crontab Cheatsheet

Cron Format

Use five time fields followed by the command.

Format Description
* * * * * command min hour day month weekday command
* Any value
, List of values (for example 1,15)
- Range of values (for example 1-5)
/ Step values (for example */10)

Time Fields

Valid ranges for each cron field.

Field Allowed Values
Minute 0-59
Hour 0-23
Day of month 1-31
Month 1-12 or JAN-DEC
Day of week 0-7 (0 and 7 are Sunday) or SUN-SAT

Special Schedule Strings

Shortcuts for common schedules.

String Equivalent Description
@reboot N/A Run once at startup
@yearly 0 0 1 1 * Run once a year
@annually 0 0 1 1 * Same as @yearly
@monthly 0 0 1 * * Run once a month
@weekly 0 0 * * 0 Run once a week
@daily 0 0 * * * Run once a day
@midnight 0 0 * * * Same as @daily
@hourly 0 * * * * Run once an hour

Common Schedules

Frequently used cron expressions.

Schedule Cron Expression
Every minute * * * * *
Every 5 minutes */5 * * * *
Every 15 minutes */15 * * * *
Every hour at minute 0 0 * * * *
Every day at 02:30 30 2 * * *
Every weekday at 09:00 0 9 * * 1-5
Every Sunday at 03:00 0 3 * * 0
First day of month at midnight 0 0 1 * *
Every 6 hours 0 */6 * * *
Every month on day 15 at 06:00 0 6 15 * *

Crontab Management

Create, list, and remove per-user cron jobs.

Command Description
crontab -e Edit current user’s crontab
crontab -l List current user’s crontab
crontab -r Remove current user’s crontab
crontab -u username -l List another user’s crontab (root)
crontab -u username -e Edit another user’s crontab (root)
crontab file.txt Install crontab from file

Command Patterns

Useful patterns for reliable cron jobs.

Pattern Description
*/5 * * * * /path/script.sh Run script every 5 minutes
0 2 * * * /path/backup.sh >> /var/log/backup.log 2>&1 Append stdout/stderr to a log
0 1 * * * /usr/bin/flock -n /tmp/job.lock /path/job.sh Prevent overlapping runs
@reboot /usr/bin/sleep 30 && /path/startup.sh Run shortly after boot
MAILTO=\"admin@example.com\" Send job output by email

Environment in Cron

Define environment values at the top of crontab.

Entry Description
SHELL=/bin/bash Use Bash for job execution
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin Set explicit command path
MAILTO=\"\" Disable cron email
CRON_TZ=Europe/Skopje Set timezone for this crontab

Troubleshooting Checks

Quick checks when jobs do not run.

Check Command
Validate cron service status systemctl status cron or systemctl status crond
Check cron logs (Debian/Ubuntu) grep CRON /var/log/syslog
Check cron logs (RHEL/Fedora) grep CROND /var/log/cron
Check script permissions ls -l /path/script.sh
Test script manually /path/script.sh
Check if @reboot ran journalctl -u cron --since "today"

Related Guides

Use these articles for complete cron workflows.

Guide Description
Scheduling Cron Jobs with Crontab Full guide to creating and managing cron jobs
How to List Cron Jobs in Linux View user and system cron jobs
Cron Jobs Every 5, 10, 15 Minutes Ready-made recurring interval examples

Wget Cheatsheet

Basic Downloads

Download files to the current directory.

Command Description
wget URL Download a file
wget -q URL Download silently (no output)
wget -nv URL Less verbose (errors and basic info only)
wget -v URL Verbose output (default)
wget -d URL Debug output

Save Options

Control where and how files are saved.

Command Description
wget -O name.txt URL Save with a specific filename
wget -O - URL Output to stdout
wget -P /path/ URL Save to a specific directory
wget --content-disposition URL Use server-suggested filename
wget --no-clobber URL Skip if file already exists
wget -nc URL Short form of --no-clobber

Resume and Speed

Resume interrupted downloads and control bandwidth.

Command Description
wget -c URL Resume a partial download
wget --limit-rate=2m URL Limit speed to 2 MB/s
wget --limit-rate=500k URL Limit speed to 500 KB/s
wget -b URL Download in background
wget -b -o log.txt URL Background with custom log

Multiple Files

Download several files at once.

Command Description
wget URL1 URL2 URL3 Download multiple URLs
wget -i urls.txt Download URLs from a file
wget -i - < urls.txt Read URLs from stdin

Recursive Download

Download directory trees and linked pages.

Command Description
wget -r URL Recursive download
wget -r -l 2 URL Limit depth to 2 levels
wget -r --no-parent URL Do not ascend to parent directory
wget -r --accept=jpg,png URL Accept only these file types
wget -r --reject=mp4,avi URL Reject these file types
wget -r -A "*.pdf" URL Download only PDFs
wget -r --follow-tags=a URL Follow only <a> tags

Website Mirroring

Create offline copies of websites.

Command Description
wget -m URL Mirror a website
wget -m -k -p URL Mirror with local link conversion
wget -m -k -p -E URL Mirror and add .html extensions
wget -m --wait=2 URL Mirror with 2 second delay between requests
wget -m --random-wait URL Mirror with random delay (0.5x–1.5x of --wait)

Authentication

Access protected resources.

Command Description
wget --user=USER --password=PASS URL HTTP basic auth
wget --ask-password URL Prompt for password
wget --header="Authorization: Bearer TOKEN" URL Token auth
wget --ftp-user=USER --ftp-password=PASS URL FTP auth

Headers and User Agent

Send custom headers and change identity.

Command Description
wget --header="Key: Value" URL Add custom header
wget --header="Accept: application/json" URL Request JSON
wget -U "CustomAgent/1.0" URL Change user agent
wget --referer=URL URL Set referer header

SSL/TLS

Handle HTTPS connections and certificates.

Command Description
wget --no-check-certificate URL Skip certificate verification
wget --ca-certificate=ca.crt URL Use custom CA certificate
wget --certificate=client.crt URL Client certificate
wget --private-key=client.key URL Client private key
wget --https-only URL Only follow HTTPS links

FTP

Work with FTP servers.

Command Description
wget ftp://server/file Download file
wget -r ftp://server/dir/ Download directory recursively
wget --ftp-user=USER --ftp-password=PASS ftp://server/ Authenticated FTP
wget --no-passive-ftp ftp://server/file Use active FTP mode
wget --no-remove-listing ftp://server/dir/ Keep .listing files

Retries and Timeouts

Control retry behavior and connection timing.

Command Description
wget --tries=5 URL Retry up to 5 times
wget --retry-connrefused URL Retry on connection refused
wget --waitretry=10 URL Wait 10 seconds between retries
wget --timeout=30 URL Set all timeouts to 30 seconds
wget --connect-timeout=10 URL Connection timeout only
wget --read-timeout=30 URL Read timeout only
wget --dns-timeout=5 URL DNS timeout only

Output and Logging

Control progress display and log output.

Command Description
wget -q URL Suppress all output
wget -nv URL Print errors and basic info only
wget -o log.txt URL Log output to file
wget -a log.txt URL Append to log file
wget --show-progress -q URL Quiet but show progress bar
wget --progress=dot URL Dot-style progress indicator

Timestamping and Caching

Download only new or updated files.

Command Description
wget -N URL Download only if remote file is newer
wget --no-cache URL Disable server-side caching
wget --spider URL Check if URL exists (do not download)
wget --spider -r URL Check all links recursively

Common Patterns

Frequently used command combinations.

Command Description
wget -q -O - URL | tar -xzf - -C /path Download and extract in one step
wget -c --limit-rate=1m -P /tmp URL Resume to directory with speed limit
wget -r -np -nH --cut-dirs=2 URL Recursive without host and path prefix
wget -m -k -p --wait=1 -e robots=off URL Full mirror ignoring robots.txt

Related Guides

Use these articles for detailed wget workflows.

Guide Description
Wget Command in Linux with Examples Full wget tutorial with practical examples
Curl Command in Linux with Examples Alternative HTTP client for API interactions
How to Use SCP Command to Securely Transfer Files Transfer files between hosts over SSH
How to Use Rsync for Local and Remote Data Transfer Incremental file sync and transfer

Tar Cheatsheet

Basic Syntax

Core tar command forms.

Command Description
tar -cf archive.tar files/ Create archive
tar -xf archive.tar Extract archive
tar -tf archive.tar List archive contents
tar -rf archive.tar file.txt Append file to archive (uncompressed only)
tar --delete -f archive.tar file.txt Remove file from archive (uncompressed only)

Create Archives

Common archive creation patterns.

Command Description
tar -cf backup.tar /etc /var/www Archive multiple paths
tar -cf project.tar project/ Archive a directory
tar -cvf project.tar project/ Verbose create
tar -cf archive.tar --files-from=filelist.txt Create from file list
tar -cf archive.tar --exclude="*.log" app/ Exclude pattern while creating

Extract Archives

Extract all files or selected paths.

Command Description
tar -xf archive.tar Extract in current directory
tar -xvf archive.tar Verbose extraction
tar -xf archive.tar -C /tmp/restore Extract to target directory
tar -xf archive.tar path/in/archive.txt Extract one file
tar -xf archive.tar "dir/*" Extract matching path pattern
tar -xf archive.tar --strip-components=1 Strip leading directory from paths

List and Inspect

Check what is inside an archive.

Command Description
tar -tf archive.tar List files
tar -tvf archive.tar Detailed list with metadata
tar -tf archive.tar | head Preview first entries
tar -tf archive.tar | grep nginx Find matching archive paths
tar --compare -f archive.tar Compare archive with filesystem

Compression Formats

Use gzip, bzip2, and xz with tar.

Command Description
tar -czf backup.tar.gz /data Create .tar.gz
tar -xzf backup.tar.gz Extract .tar.gz
tar -cjf backup.tar.bz2 /data Create .tar.bz2
tar -xjf backup.tar.bz2 Extract .tar.bz2
tar -cJf backup.tar.xz /data Create .tar.xz
tar -xJf backup.tar.xz Extract .tar.xz

Preserve Metadata

Keep permissions, ownership, and timestamps.

Command Description
tar -cpf system.tar /etc /var Archive system paths preserving permissions
tar -xpf rootfs.tar Extract and preserve permissions
tar --numeric-owner -cpf backup.tar /srv Store numeric UID/GID
tar --same-owner -xpf backup.tar Keep original ownership on extract
tar --atime-preserve=system -cf backup.tar /data Preserve file access times

Incremental Backups

Create snapshot-based incremental archives.

Command Description
tar --listed-incremental=snapshot.snar -cf full.tar /home Create initial full backup
tar --listed-incremental=snapshot.snar -cf inc-1.tar /home Create next incremental backup
tar -tf inc-1.tar List incremental archive entries
tar -xf full.tar -C /restore Restore full backup
tar -xf inc-1.tar -C /restore Apply incremental backup

Exclude Patterns

Skip files and directories during archive creation.

Command Description
tar -cf app.tar app/ --exclude="*.tmp" Exclude by extension
tar -cf app.tar app/ --exclude="cache/*" Exclude path pattern
tar -cf app.tar app/ --exclude-vcs Exclude VCS dirs (.git, etc.)
tar -cf app.tar app/ --exclude-from=exclude.txt Exclude using a patterns file
tar -czf logs.tar.gz /var/log --exclude="*.gz" Archive logs without already-compressed files

Safety and Verification

Run safer extraction and validation commands.

Command Description
tar -tvf archive.tar Inspect archive before extracting
tar -xf archive.tar --keep-old-files Do not overwrite existing files
tar -xf archive.tar --skip-old-files Skip files that already exist
tar -xf archive.tar --warning=no-unknown-keyword Suppress noisy keyword warnings
tar -tzf backup.tar.gz > /dev/null Quick integrity check for .tar.gz

Remote Transfer

Pipe tar over SSH for direct server-to-server transfers.

Command Description
tar -czf - /data | ssh user@host "cat > backup.tar.gz" Archive and send to remote host
ssh user@host "tar -czf - /data" | tar -xzf - -C /local/path Pull and extract from remote host
tar -cf - /data | ssh user@host "tar -xf - -C /restore" Stream archive directly to remote

Common Options

Useful flags and what they do.

Option Description
-c Create archive
-x Extract archive
-t List archive contents
-f Use archive file
-v Verbose output
-z Gzip compression
-j Bzip2 compression
-J XZ compression
-C Change to directory before operation
-p Preserve permissions

Related Guides

Use these articles for step-by-step tar workflows.

Guide Description
How to Create and Extract Archives Using the tar Command in Linux Full tar tutorial with examples
How to Create tar.gz File Focused .tar.gz creation guide
How to Extract/Unzip tar.gz File .tar.gz extraction patterns

Screen Cheatsheet

Start and Exit

Command Description
screen Start a new screen session
screen -S work Start session named work
screen -ls List running sessions
screen -X -S work quit Stop session work
exit Exit current shell/window

Attach and Detach

Command Description
screen -r Reattach to the only detached session
screen -r work Reattach to named session
screen -x work Attach to an already-attached session
screen -d -r work Detach elsewhere and reattach here
Ctrl+a d Detach current session

Prefix and Help

Default prefix is Ctrl+a.

Key Description
Ctrl+a Enter screen command mode
Ctrl+a ? Show key bindings help
Ctrl+a : Open command prompt
Ctrl+a " Show window list

Windows

Key / Command Description
Ctrl+a c Create a new window
Ctrl+a n Next window
Ctrl+a p Previous window
Ctrl+a Ctrl+a Switch to last window
Ctrl+a 0-9 Switch to window by number
Ctrl+a A Rename current window
Ctrl+a k Kill current window

Navigation and Layout

Key Description
Ctrl+a w List windows in status line
Ctrl+a ' Prompt for window number
Ctrl+a S Split display horizontally
Ctrl+a | Split display vertically
Ctrl+a Tab Move between split regions
Ctrl+a X Remove current region
Ctrl+a Q Remove all regions except current

Copy and Scrollback

Key Description
Ctrl+a [ Enter copy/scrollback mode
Space Start selection (in copy mode)
Enter Copy selection (in copy mode)
Ctrl+a ] Paste copied text
Ctrl+a H Toggle logging to file

Session Management

Command Description
screen -wipe Clean dead sessions
Ctrl+a x Lock session
screen -S work -X stuff 'ls^M' Send command to session (^M = Enter)
screen -S work -p 0 -X hardcopy Save current window output

Useful Patterns

Command Description
screen -dmS job bash -lc 'long-command' Start detached background job
screen -D -R Reattach if possible, otherwise create
screen -r work -p 2 Attach directly to window 2
screen -L Start session with logging enabled

Configuration

File / Command Description
~/.screenrc User configuration file
defscrollback 10000 Increase scrollback history
hardstatus on Enable status line
startup_message off Disable startup message

FTP Cheatsheet

Connect and Login

Start an FTP session and authenticate.

Command Description
ftp hostname Connect to server
ftp 192.168.1.10 Connect by IP
ftp hostname 21 Connect to a custom port
user username Log in with username (prompts for password)
user username password Log in with username and password
quit Quit session
bye Quit session (alias for quit)

Local and Remote Paths

Navigate directories on both sides.

Command Description
pwd Show remote working directory
!pwd Show local working directory
cd /remote/path Change remote directory
lcd /local/path Change local directory
ls List remote files
!ls List local files

Download Files

Transfer files from remote server to local system.

Command Description
get file.txt Download one file
get remote.txt local.txt Download and rename locally
mget *.log Download multiple files
prompt Toggle interactive prompt for mget
reget large.iso Resume interrupted download

Upload Files

Transfer local files to remote server.

Command Description
put file.txt Upload one file
put local.txt remote.txt Upload with remote name
mput *.txt Upload multiple files
append file.txt Append local file to remote file

Transfer Modes

Select ASCII or binary mode as needed.

Command Description
binary Set binary transfer mode
ascii Set text transfer mode
type Show current transfer mode
hash Show transfer progress marks
status Display session and transfer status

Remote File Management

Manage files and directories on the FTP server.

Command Description
mkdir dirname Create remote directory
rmdir dirname Remove remote directory
delete file.txt Delete remote file
mdelete *.tmp Delete multiple remote files
rename old.txt new.txt Rename remote file
size file.iso Show remote file size

Connection and Safety

Useful options to avoid transfer issues.

Command Description
passive Toggle passive mode
debug Toggle protocol debug output
verbose Toggle verbose transfer output
close Close connection, keep FTP shell
open hostname Reconnect to another host
!command Run a local shell command
help List available FTP commands

Batch and Non-Interactive

Run FTP commands from scripts.

Command Description
ftp -n hostname Disable auto-login
ftp -inv hostname Script-friendly mode
ftp hostname < commands.txt Run commands from file

Related Tools

Safer and encrypted alternatives when possible.

Tool Description
sftp SSH-based secure file transfer
scp Secure copy over SSH
rsync Efficient sync and incremental transfer

How to Parse Command-Line Options in Bash with getopts

The getopts command is a Bash built-in that provides a clean, structured way to parse command-line options in your scripts. Instead of manually looping through arguments with case and shift, getopts handles option parsing, argument extraction, and error reporting for you.

This guide explains how to use getopts to process options and arguments in Bash scripts. If you are new to command-line arguments, start with our guide on positional parameters .

Syntax

The basic syntax for getopts is:

sh
while getopts "optstring" VARNAME; do
 case $VARNAME in
 # handle each option
 esac
done
  • optstring — A string that defines which options the script accepts
  • VARNAME — A variable that holds the current option letter on each iteration

Each time the while loop runs, getopts processes the next option from the command line and stores the option letter in VARNAME. The loop ends when there are no more options to process.

Here is a simple example:

~/flags.shsh
#!/bin/bash

while getopts "vh" opt; do
 case $opt in
 v) echo "Verbose mode enabled" ;;
 h) echo "Usage: $0 [-v] [-h]"; exit 0 ;;
 esac
done

Run the script:

Terminal
./flags.sh -v
./flags.sh -h
./flags.sh -vh
output
Verbose mode enabled
Usage: ./flags.sh [-v] [-h]
Verbose mode enabled
Usage: ./flags.sh [-v] [-h]

Notice that -vh works the same as -v -h. The getopts command automatically handles combined short options.

The Option String

The option string tells getopts which option letters are valid and which ones require an argument. There are three patterns:

  • f — A simple flag (no argument). Used for boolean switches like -v for verbose.
  • f: — An option that requires an argument. The colon after the letter means the user must provide a value, such as -f filename.
  • : (leading colon) — Enables silent error mode. When placed at the very beginning of the option string, getopts suppresses its default error messages so you can handle errors yourself.

For example, the option string ":vf:o:" means:

  • : — Silent error mode
  • v — A simple flag (-v)
  • f: — An option requiring an argument (-f filename)
  • o: — An option requiring an argument (-o output)

OPTARG and OPTIND

When working with getopts, two special variables track the parsing state:

OPTARG

The OPTARG variable holds the argument value for options that require one. When you define an option with a trailing colon (e.g., f:), the value the user passes after -f is stored in OPTARG:

~/optarg_example.shsh
#!/bin/bash

while getopts "f:o:" opt; do
 case $opt in
 f) echo "Input file: $OPTARG" ;;
 o) echo "Output file: $OPTARG" ;;
 esac
done
Terminal
./optarg_example.sh -f data.csv -o results.txt
output
Input file: data.csv
Output file: results.txt

OPTIND

The OPTIND variable holds the index of the next argument to be processed. It starts at 1 and increments as getopts processes each option. After the while loop finishes, OPTIND points to the first non-option argument.

Use shift $((OPTIND - 1)) after the loop to remove all processed options, leaving only the remaining positional arguments in $@:

~/optind_example.shsh
#!/bin/bash

while getopts "v" opt; do
 case $opt in
 v) echo "Verbose mode enabled" ;;
 esac
done

shift $((OPTIND - 1))

echo "Remaining arguments: $@"
Terminal
./optind_example.sh -v file1.txt file2.txt
output
Verbose mode enabled
Remaining arguments: file1.txt file2.txt

The shift $((OPTIND - 1)) line is a common pattern. Without it, the processed options would still be part of the positional parameters, making it difficult to access the non-option arguments.

Error Handling

The getopts command has two error handling modes: verbose (default) and silent.

Verbose Mode (Default)

In verbose mode, getopts prints its own error messages when it encounters an invalid option or a missing argument:

~/verbose_errors.shsh
#!/bin/bash

while getopts "f:" opt; do
 case $opt in
 f) echo "File: $OPTARG" ;;
 esac
done
Terminal
./verbose_errors.sh -x
./verbose_errors.sh -f
output
./verbose_errors.sh: illegal option -- x
./verbose_errors.sh: option requires an argument -- f

In this mode, getopts sets opt to ? for both invalid options and missing arguments.

Silent Mode

Silent mode is enabled by adding a colon at the beginning of the option string. In this mode, getopts suppresses its default error messages and gives you more control:

  • For an invalid option, opt is set to ? and OPTARG contains the invalid option character.
  • For a missing argument, opt is set to : and OPTARG contains the option that was missing its argument.
~/silent_errors.shsh
#!/bin/bash

while getopts ":f:vh" opt; do
 case $opt in
 f) echo "File: $OPTARG" ;;
 v) echo "Verbose mode" ;;
 h) echo "Usage: $0 [-v] [-f file] [-h]"; exit 0 ;;
 \?) echo "Error: Invalid option -$OPTARG" >&2; exit 1 ;;
 :) echo "Error: Option -$OPTARG requires an argument" >&2; exit 1 ;;
 esac
done
Terminal
./silent_errors.sh -x
./silent_errors.sh -f
output
Error: Invalid option -x
Error: Option -f requires an argument

Silent mode is the recommended approach for production scripts because it allows you to write custom error messages that are more helpful to the user.

Practical Examples

Example 1: Script with Flags and Arguments

This script demonstrates a common pattern — a usage function , boolean flags, options with arguments, and input validation:

~/process.shsh
#!/bin/bash

usage() {
 echo "Usage: $0 [-v] [-o output] [-n count] file..."
 echo ""
 echo "Options:"
 echo " -v Enable verbose output"
 echo " -o output Write results to output file"
 echo " -n count Number of lines to process"
 echo " -h Show this help message"
 exit 1
}

VERBOSE=false
OUTPUT=""
COUNT=0

while getopts ":vo:n:h" opt; do
 case $opt in
 v) VERBOSE=true ;;
 o) OUTPUT="$OPTARG" ;;
 n) COUNT="$OPTARG" ;;
 h) usage ;;
 \?) echo "Error: Invalid option -$OPTARG" >&2; usage ;;
 :) echo "Error: Option -$OPTARG requires an argument" >&2; usage ;;
 esac
done

shift $((OPTIND - 1))

if [ $# -eq 0 ]; then
 echo "Error: No input files specified" >&2
 usage
fi

if [ "$VERBOSE" = true ]; then
 echo "Verbose: ON"
 echo "Output: ${OUTPUT:-stdout}"
 echo "Count: ${COUNT:-all}"
 echo "Files: $@"
 echo ""
fi

for file in "$@"; do
 if [ ! -f "$file" ]; then
 echo "Warning: '$file' not found, skipping" >&2
 continue
 fi

 if [ -n "$OUTPUT" ]; then
 if [ "$COUNT" -gt 0 ] 2>/dev/null; then
 head -n "$COUNT" "$file" >> "$OUTPUT"
 else
 cat "$file" >> "$OUTPUT"
 fi
 else
 if [ "$COUNT" -gt 0 ] 2>/dev/null; then
 head -n "$COUNT" "$file"
 else
 cat "$file"
 fi
 fi
done
Terminal
echo -e "line 1\nline 2\nline 3\nline 4\nline 5" > testfile.txt
./process.sh -v -n 3 testfile.txt
output
Verbose: ON
Output: stdout
Count: 3
Files: testfile.txt
line 1
line 2
line 3

The script parses the options first, then uses shift to access the remaining file arguments.

Example 2: Configuration Wrapper

This example shows a script that wraps another command, passing different configurations based on the options provided:

~/deploy.shsh
#!/bin/bash

ENV="staging"
DRY_RUN=false
TAG="latest"

while getopts ":e:t:dh" opt; do
 case $opt in
 e) ENV="$OPTARG" ;;
 t) TAG="$OPTARG" ;;
 d) DRY_RUN=true ;;
 h)
 echo "Usage: $0 [-e environment] [-t tag] [-d] service"
 echo ""
 echo " -e env Target environment (default: staging)"
 echo " -t tag Image tag (default: latest)"
 echo " -d Dry run mode"
 exit 0
 ;;
 \?) echo "Error: Invalid option -$OPTARG" >&2; exit 1 ;;
 :) echo "Error: Option -$OPTARG requires an argument" >&2; exit 1 ;;
 esac
done

shift $((OPTIND - 1))

SERVICE="${1:?Error: Service name required}"

echo "Deploying '$SERVICE' to $ENV with tag '$TAG'"

if [ "$DRY_RUN" = true ]; then
 echo "[DRY RUN] Would execute: docker pull myregistry/$SERVICE:$TAG"
 echo "[DRY RUN] Would execute: kubectl set image deployment/$SERVICE $SERVICE=myregistry/$SERVICE:$TAG -n $ENV"
else
 echo "Pulling image and updating deployment..."
fi
Terminal
./deploy.sh -e production -t v2.1.0 -d webapp
output
Deploying 'webapp' to production with tag 'v2.1.0'
[DRY RUN] Would execute: docker pull myregistry/webapp:v2.1.0
[DRY RUN] Would execute: kubectl set image deployment/webapp webapp=myregistry/webapp:v2.1.0 -n production

getopts vs getopt

The getopts built-in is often confused with the external getopt command. Here are the key differences:

Feature getopts (built-in) getopt (external)
Type Bash/POSIX built-in External program (/usr/bin/getopt)
Long options Not supported Supported (--verbose)
Portability Works on all POSIX shells Varies by OS (GNU vs BSD)
Whitespace handling Handles correctly GNU version handles correctly
Error handling Built-in verbose/silent modes Manual
Speed Faster (no subprocess) Slower (spawns a process)

Use getopts when you only need short options and want maximum portability. Use getopt (GNU version) when you need long options like --verbose or --output.

Troubleshooting

Options are not being parsed
Make sure your options come before any non-option arguments. The getopts command stops parsing when it encounters the first non-option argument. For example, ./script.sh file.txt -v will not parse -v because file.txt comes first.

OPTIND is not resetting between function calls
If you use getopts inside a function and call that function multiple times, you need to reset OPTIND to 1 before each call. Otherwise, getopts will start from where it left off.

Missing argument not detected
If an option requires an argument but getopts does not report an error, check that you included a colon after the option letter in the option string. For example, use "f:" instead of "f" if -f needs an argument.

Unexpected ? in the variable
In verbose mode (no leading colon), getopts sets the variable to ? for both invalid options and missing arguments. Switch to silent mode (leading colon) to distinguish between the two cases and write custom error messages.

Quick Reference

Element Description
getopts "opts" var Parse options defined in opts, store current letter in var
f in option string Simple flag, no argument
f: in option string Option that requires an argument
: (leading) Enable silent error mode
$OPTARG Holds the argument for the current option
$OPTIND Index of the next argument to process
shift $((OPTIND - 1)) Remove parsed options, keep remaining arguments
\? in case Handles invalid options
: in case Handles missing arguments (silent mode only)

FAQ

Does getopts support long options like –verbose?
No. The getopts built-in only supports single-character options (e.g., -v). For long options, use the external getopt command (GNU version) or parse them manually with a case statement and shift.

Can I combine options like -vf file?
Yes. The getopts command automatically handles combined options. When it encounters -vf file, it processes -v first, then -f with file as its argument.

What happens if I forget shift $((OPTIND - 1))?
The processed options will remain in the positional parameters. Any code that accesses $1, $2, or $@ after the getopts loop will still see the option flags instead of just the remaining arguments.

Is getopts POSIX compliant?
Yes. The getopts command is defined by the POSIX standard and works in all POSIX-compliant shells, including bash, dash, ksh, and zsh. This makes it more portable than the external getopt command.

How do I make an option’s argument optional?
The getopts built-in does not support optional arguments for options. An option either always requires an argument (using :) or never takes one. If you need optional arguments, handle the logic manually after parsing.

Conclusion

The getopts built-in provides a reliable way to parse command-line options in Bash scripts. It handles option string definitions, argument extraction, combined flags, and error reporting with minimal code.

If you have any questions, feel free to leave a comment below.

How to Revert a Commit in Git

The git revert command creates a new commit that undoes the changes introduced by a specified commit. Unlike git reset , which rewrites the commit history, git revert preserves the full history and is the safe way to undo changes that have already been pushed to a shared repository.

This guide explains how to use git revert to undo one or more commits with practical examples.

Quick Reference

Task Command
Revert the last commit git revert HEAD
Revert without opening editor git revert --no-edit HEAD
Revert a specific commit git revert COMMIT_HASH
Revert without committing git revert --no-commit HEAD
Revert a range of commits git revert --no-commit HEAD~3..HEAD
Revert a merge commit git revert -m 1 MERGE_COMMIT_HASH
Abort a revert in progress git revert --abort
Continue after resolving conflicts git revert --continue

Syntax

The general syntax for the git revert command is:

Terminal
git revert [OPTIONS] COMMIT
  • OPTIONS — Flags that modify the behavior of the command.
  • COMMIT — The commit hash or reference to revert.

git revert vs git reset

Before diving into examples, it is important to understand the difference between git revert and git reset, as they serve different purposes:

  • git revert — Creates a new commit that undoes the changes from a previous commit. The original commit remains in the history. This is safe to use on branches that have been pushed to a remote repository.
  • git reset — Moves the HEAD pointer backward, effectively removing commits from the history. This rewrites the commit history and should not be used on shared branches without coordinating with your team.

As a general rule, use git revert for commits that have already been pushed, and git reset for local commits that have not been shared.

Reverting the Last Commit

To revert the most recent commit, run git revert followed by HEAD:

Terminal
git revert HEAD

Git will open your default text editor so you can edit the revert commit message. The default message looks like this:

plain
Revert "Original commit message"

This reverts commit abc1234def5678...

Save and close the editor to complete the revert. Git will create a new commit that reverses the changes from the last commit.

To verify the revert, use git log to see the new revert commit in the history:

Terminal
git log --oneline -3
output
a1b2c3d (HEAD -> main) Revert "Add new feature"
f4e5d6c Add new feature
b7a8c9d Update configuration

The original commit (f4e5d6c) remains in the history, and the new revert commit (a1b2c3d) undoes its changes.

Reverting a Specific Commit

You do not have to revert the most recent commit. You can revert any commit in the history by specifying its commit hash.

First, find the commit hash using git log:

Terminal
git log --oneline
output
a1b2c3d (HEAD -> main) Update README
f4e5d6c Add login feature
b7a8c9d Fix navigation bug
e0f1a2b Add search functionality

To revert the “Fix navigation bug” commit, pass its hash to git revert:

Terminal
git revert b7a8c9d

Git will create a new commit that undoes only the changes introduced in commit b7a8c9d, leaving all other commits intact.

Reverting Without Opening an Editor

If you want to use the default revert commit message without opening an editor, use the --no-edit option:

Terminal
git revert --no-edit HEAD
output
[main d5e6f7a] Revert "Add new feature"
2 files changed, 0 insertions(+), 15 deletions(-)

This is useful when scripting or when you do not need a custom commit message.

Reverting Without Committing

By default, git revert automatically creates a new commit. If you want to stage the reverted changes without committing them, use the --no-commit (or -n) option:

Terminal
git revert --no-commit HEAD

The changes will be applied to the working directory and staging area, but no commit is created. You can then review the changes, make additional modifications, and commit manually:

Terminal
git status
git commit -m "Revert feature and clean up related code"

This is useful when you want to combine the revert with other changes in a single commit.

Reverting Multiple Commits

Reverting a Range of Commits

To revert a range of consecutive commits, specify the range using the .. notation:

Terminal
git revert --no-commit HEAD~3..HEAD

This reverts the last three commits. The --no-commit option stages all the reverted changes without creating individual revert commits, allowing you to commit them as a single revert:

Terminal
git commit -m "Revert last three commits"

Without --no-commit, Git will create a separate revert commit for each commit in the range.

Reverting Multiple Individual Commits

To revert multiple specific (non-consecutive) commits, list them one after another:

Terminal
git revert --no-commit abc1234 def5678 ghi9012
git commit -m "Revert selected commits"

Reverting a Merge Commit

Merge commits have two parent commits, so Git needs to know which parent to revert to. Use the -m option followed by the parent number (usually 1 for the branch you merged into):

Terminal
git revert -m 1 MERGE_COMMIT_HASH

In the following example, we revert a merge commit and keep the main branch as the base:

Terminal
git revert -m 1 a1b2c3d
  • -m 1 — Tells Git to use the first parent (the branch the merge was made into, typically main or master) as the base.
  • -m 2 — Would use the second parent (the branch that was merged in).

You can check the parents of a merge commit using:

Terminal
git log --oneline --graph

Handling Conflicts During Revert

If the code has changed since the original commit, Git may encounter conflicts when applying the revert. When this happens, Git will pause the revert and show conflicting files:

output
CONFLICT (content): Merge conflict in src/app.js
error: could not revert abc1234... Add new feature
hint: After resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' and run 'git revert --continue'.

To resolve the conflict:

  1. Open the conflicting files and resolve the merge conflicts manually.

  2. Stage the resolved files:

    Terminal
    git add src/app.js
  3. Continue the revert:

    Terminal
    git revert --continue

If you decide not to proceed with the revert, you can abort it:

Terminal
git revert --abort

This restores the repository to the state before you started the revert.

Pushing a Revert to a Remote Repository

Since git revert creates a new commit rather than rewriting history, you can safely push it to a shared repository using a regular push:

Terminal
git push origin main

There is no need for --force because the commit history is not rewritten.

Common Options

The git revert command accepts several options:

  • --no-edit — Use the default commit message without opening an editor.
  • --no-commit (-n) — Apply the revert to the working directory and index without creating a commit.
  • -m parent-number — Specify which parent to use when reverting a merge commit (usually 1).
  • --abort — Cancel the revert operation and return to the pre-revert state.
  • --continue — Continue the revert after resolving conflicts.
  • --skip — Skip the current commit and continue reverting the rest.

Troubleshooting

Revert is in progress
If you see a message that a revert is in progress, either continue with git revert --continue after resolving conflicts or cancel with git revert --abort.

Revert skips a commit
If Git reports that a commit was skipped because it was already applied, it means the changes are already present. You can proceed or use git revert --skip to continue.

FAQ

What is the difference between git revert and git reset?
git revert creates a new commit that undoes changes while preserving the full commit history. git reset moves the HEAD pointer backward and can remove commits from the history. Use git revert for shared branches and git reset for local, unpushed changes.

Can I revert a commit that has already been pushed?
Yes. This is exactly what git revert is designed for. Since it creates a new commit rather than rewriting history, it is safe to push to shared repositories without disrupting other collaborators.

How do I revert a merge commit?
Use the -m option to specify the parent number. For example, git revert -m 1 MERGE_HASH reverts the merge and keeps the first parent (usually the main branch) as the base.

Can I undo a git revert?
Yes. Since a revert is just a regular commit, you can revert the revert commit itself: git revert REVERT_COMMIT_HASH. This effectively re-applies the original changes.

What happens if there are conflicts during a revert?
Git will pause the revert and mark the conflicting files. You need to resolve the conflicts manually, stage the files with git add, and then run git revert --continue to complete the operation.

Conclusion

The git revert command is the safest way to undo changes in a Git repository, especially for commits that have already been pushed. It creates a new commit that reverses the specified changes while keeping the full commit history intact.

If you have any questions, feel free to leave a comment below.

Find Cheatsheet

Basic Search

Find files and directories by name.

Command Description
find . -name "file.txt" Find an exact filename
find . -iname "readme.md" Case-insensitive name search
find /etc -name "*.conf" Find by extension
find . -type d -name "backup" Find directories by name

Filter by Type

Limit results to file system object type.

Command Description
find . -type f Regular files only
find . -type d Directories only
find . -type l Symlinks only
find . -type f -name "*.log" Files with a specific extension
find . -maxdepth 1 -type f Search current directory only
find . -type f -empty Find empty files
find . -type d -empty Find empty directories

Size Filters

Find files by size.

Command Description
find . -type f -size +100M Larger than 100 MB
find . -type f -size -10M Smaller than 10 MB
find . -type f -size 1G Exactly 1 GB
find /var -type f -size +500M Large files under /var

Time Filters

Filter by file modification, access, and change times.

Command Description
find . -type f -mtime -7 Modified in last 7 days
find . -type f -mtime +30 Modified more than 30 days ago
find . -type f -atime -1 Accessed in last 24 hours
find . -type f -ctime -3 Metadata changed in last 3 days
find . -type f -mmin -60 Modified in last 60 minutes

Permissions and Ownership

Find files based on permissions and owners.

Command Description
find . -type f -perm 644 Exact permission match
find . -type f -perm -u+w User-writable files
find / -type f -user root Files owned by user
find /srv -type f -group www-data Files owned by group

Excluding Paths

Skip directories from search results.

Command Description
find . -path ./node_modules -prune -o -type f -print Exclude one directory
find . \( -path ./node_modules -o -path ./.git \) -prune -o -type f -print Exclude multiple directories
find . -type f ! -name "*.log" Exclude one filename pattern
find . -type f ! -path "*/cache/*" Exclude by path pattern

Actions (-exec, -delete)

Run commands on matched files.

Command Description
find . -type f -name "*.tmp" -delete Delete matches
find . -type f -name "*.log" -exec gzip {} \; Run command per file
find . -type f -name "*.jpg" -exec mv {} /tmp/images/ \; Move matched files
find . -type f -name "*.conf" -exec grep -H "listen" {} \; Search text in matched files
find . -type f -name "*.log" -exec rm {} + Batch delete (faster than \;)

Safer Bulk Operations

Use null-delimited output for safe piping.

Command Description
find . -type f -name "*.txt" -print0 | xargs -0 rm -f Safely remove files with spaces
find . -type f -print0 | xargs -0 ls -lh Safe batch listing
find . -type f -name "*.log" -print0 | xargs -0 du -h Safe size report for matches
find . -type f -name "*.bak" -print0 | xargs -0 -I{} mv "{}" /tmp/backup/ Safe batch move

Common Options

Useful flags to remember.

Option Description
-name Match filename (case-sensitive)
-iname Match filename (case-insensitive)
-type Filter by file type
-size Filter by size
-mtime Filter by modification time (days)
-maxdepth Limit recursion depth
-mindepth Skip top levels
-prune Exclude directories
-exec Execute command on matches
-empty Find empty files/directories
-mmin Filter by modification time (minutes)
-delete Delete matched files

Git Cheatsheet

Getting Started

Initialize and configure Git.

Command Description
git init Initialize a new repository
git clone url Clone a remote repository
git status Show working tree status
git config --global user.name "Name" Set global name
git config --global user.email "email" Set global email

Staging and Committing

Add changes and create commits.

Command Description
git add file Stage a file
git add . Stage all changes
git commit -m "message" Commit staged changes
git commit --amend Amend last commit
git revert commit Revert a commit

Branches

Create, list, and switch branches.

Command Description
git branch List branches
git branch name Create a branch
git switch name Switch branch
git switch -c name Create and switch
git branch -d name Delete local branch
git branch -D name Force delete branch
git branch -m new-name Rename current branch

Merge and Rebase

Combine branches and rewrite history.

Command Description
git merge branch Merge branch into current
git merge --no-ff branch Merge with merge commit
git merge --abort Abort merge in progress
git rebase branch Rebase onto branch
git rebase -i HEAD~3 Interactive rebase last 3
git rebase --abort Abort rebase in progress
git cherry-pick commit Apply a single commit

Remote Repositories

Work with remotes and synchronization.

Command Description
git remote -v List remotes
git remote add origin url Add remote
git remote set-url origin url Change remote URL
git remote remove origin Remove remote
git fetch Fetch from remote
git pull Fetch and merge
git push Push to remote
git push -u origin branch Push and set upstream
git push origin --delete branch Delete remote branch

Stash

Temporarily save uncommitted changes.

Command Description
git stash Stash changes
git stash push -m "message" Stash with message
git stash list List stashes
git stash pop Apply and remove latest
git stash apply stash@{0} Apply without removing
git stash drop stash@{0} Delete a stash
git stash clear Delete all stashes

History and Diff

Inspect history and changes.

Command Description
git log View commit history
git log --oneline --graph Compact graph view
git log -p file History of a file
git show commit Show a commit
git blame file Show who changed each line
git reflog Show reference log (recovery)
git diff Unstaged diff
git diff --staged Staged diff
git diff branch1..branch2 Compare branches

Undo and Cleanup

Discard or reset changes safely.

Command Description
git restore file Discard local changes
git restore --staged file Unstage a file
git reset --soft HEAD~1 Undo commit, keep changes
git reset --hard HEAD Reset to last commit
git clean -fd Remove untracked files/dirs

Tags

Create and manage tags.

Command Description
git tag List tags
git tag v1.0.0 Create tag
git tag -a v1.0.0 -m "msg" Annotated tag
git push --tags Push all tags
git tag -d v1.0.0 Delete local tag
git push origin --delete v1.0.0 Delete remote tag

.gitignore

Exclude files from version control.

Pattern Description
*.log Ignore all .log files
node_modules/ Ignore directory
!important.log Negate ignore rule
**/build Ignore in any directory
git rm --cached file Untrack a tracked file

Iptables Cheatsheet

View Rules

Inspect current firewall rules.

Command Description
sudo iptables -L List rules
sudo iptables -L -n List without resolving names
sudo iptables -L -v Verbose output
sudo iptables -L -n --line-numbers Show rule numbers
sudo iptables -S Show rules as commands
sudo iptables -t nat -L -n -v View NAT rules

Default Policies

Set default policies for chains.

Command Description
sudo iptables -P INPUT DROP Default drop inbound
sudo iptables -P FORWARD DROP Default drop forwarding
sudo iptables -P OUTPUT ACCEPT Default allow outbound

Allow Traffic

Allow common inbound traffic.

Command Description
sudo iptables -A INPUT -i lo -j ACCEPT Allow loopback
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT Allow established
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT Allow SSH
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT Allow HTTP
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT Allow HTTPS
sudo iptables -A INPUT -p icmp -j ACCEPT Allow ping
sudo iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT Allow subnet

Block Traffic

Drop or reject traffic.

Command Description
sudo iptables -A INPUT -s 203.0.113.10 -j DROP Drop IP address
sudo iptables -A INPUT -s 203.0.113.0/24 -j DROP Drop subnet
sudo iptables -A INPUT -p tcp --dport 23 -j DROP Block Telnet
sudo iptables -A INPUT -p tcp --dport 25 -j REJECT Reject SMTP
sudo iptables -A INPUT -m mac --mac-source XX:XX:XX:XX:XX:XX -j DROP Block MAC address

Port Forwarding (DNAT)

Redirect traffic to a different host or port.

Command Description
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.10:80 Forward port to host
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80 Redirect local port
sudo iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -j ACCEPT Allow forwarded traffic

NAT (Masquerade)

Enable NAT for outbound traffic.

Command Description
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE NAT for interface
sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 203.0.113.1 Static NAT
sudo sysctl -w net.ipv4.ip_forward=1 Enable IP forwarding

Rate Limiting

Limit connection rates to prevent abuse.

Command Description
sudo iptables -A INPUT -p tcp --dport 22 -m limit --limit 3/min --limit-burst 3 -j ACCEPT Limit SSH attempts
sudo iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 50 -j DROP Limit connections per IP
sudo iptables -A INPUT -p icmp -m limit --limit 1/sec -j ACCEPT Limit ping rate

Logging

Log matched packets for debugging.

Command Description
sudo iptables -A INPUT -j LOG --log-prefix "IPT-DROP: " Log dropped packets
sudo iptables -A INPUT -p tcp --dport 22 -j LOG --log-prefix "SSH: " --log-level 4 Log SSH access
sudo iptables -A INPUT -m limit --limit 5/min -j LOG Log with rate limit

Delete and Insert Rules

Manage rule order and removal.

Command Description
sudo iptables -D INPUT 3 Delete rule number 3
sudo iptables -D INPUT -p tcp --dport 80 -j ACCEPT Delete by specification
sudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT Insert rule at top
sudo iptables -R INPUT 3 -p tcp --dport 443 -j ACCEPT Replace rule number 3
sudo iptables -F Flush all rules
sudo iptables -F INPUT Flush INPUT chain only

Save and Restore

Persist rules between reboots.

Command Description
sudo iptables-save > /etc/iptables/rules.v4 Save rules
sudo iptables-restore < /etc/iptables/rules.v4 Restore rules
sudo apt install iptables-persistent Auto-persist on Debian/Ubuntu
sudo service iptables save Save on RHEL and Derivatives

Editorial Policy

Linuxize publishes practical Linux tutorials and guides for system administrators, DevOps engineers, and developers. This policy explains how we research, test, update, and correct our content.

Who Writes Our Content

Linuxize was founded by Dejan Panovski , an RHCSA-certified Linux professional with over 20 years of experience as a system administrator, DevOps engineer, and technical writer. The vast majority of articles on this site are written and maintained by Dejan. Guest contributors follow the same editorial standards outlined below.

Editorial Standards

  • Accuracy first — We verify commands, outputs, and configuration examples before publication.
  • Practical focus — Articles are written for real systems and real use cases, not theoretical examples.
  • Clear steps — We present instructions in a logical order with explanations before code blocks.
  • Security awareness — We highlight risky commands and recommend safe defaults.

Testing and Verification

We test commands and workflows on real systems whenever possible. For distro-specific posts, we verify instructions on the named distribution and version. If a procedure changes across versions, we note the difference or provide separate versions.

Updates and Maintenance

We regularly review and update published articles to keep them accurate and current. Updated articles display a “Last updated” date to indicate when they were last revised. Common reasons for updates include:

  • Software version changes or deprecated commands
  • Improved procedures or better practices
  • Reader feedback and error reports
  • New sections such as FAQ, Quick Reference, or Troubleshooting

Corrections

If you find an error, outdated step, or missing detail, please contact us at hello@linuxize.com . We review corrections promptly and update the article when needed.

Contributor Guidelines

Guest submissions follow the same standards for accuracy, testing, and clarity. All submissions are reviewed for technical correctness and editorial consistency before publication.

Transparency

We do not accept sponsored content that compromises the integrity of our tutorials. Advertising is kept separate from editorial decisions.

How to Set or Change Timezone on Debian 13

A time zone is a geographic region that has the same standard time. Using the correct time zone is essential for many system tasks and processes. For example, the cron daemon uses the system’s time zone for executing cron jobs, and the timestamps in log files are based on the same time zone.

On Debian 13 (Trixie), the system’s time zone is set during the installation, but it can be easily changed at a later time.

This article explains how to set or change the time zone on Debian 13.

Quick Reference

Task Command
Check current time zone timedatectl
List all time zones timedatectl list-timezones
Filter time zones timedatectl list-timezones | grep -i "keyword"
Set time zone sudo timedatectl set-timezone Region/City
Set to UTC sudo timedatectl set-timezone Etc/UTC
Interactive method sudo dpkg-reconfigure tzdata
Verify symlink ls -l /etc/localtime

Checking the Current Time Zone

timedatectl is a command-line utility that allows you to view and change the system’s time and date. It is available on all modern systemd-based Linux systems, including Debian 13.

To view the current time zone, run the timedatectl command without any options:

Terminal
timedatectl

The output below shows that the system’s time zone is set to UTC:

output
 Local time: Sat 2026-02-07 14:30:44 UTC
Universal time: Sat 2026-02-07 14:30:44 UTC
RTC time: Sat 2026-02-07 14:30:44
Time zone: Etc/UTC (UTC, +0000)
System clock synchronized: yes
systemd-timesyncd.service active: yes
RTC in local TZ: no

The system time zone is configured by symlinking the /etc/localtime file to a binary time zone identifier in the /usr/share/zoneinfo directory. You can also check the time zone by viewing the path the symlink points to using the ls command:

Terminal
ls -l /etc/localtime
output
lrwxrwxrwx 1 root root 27 Feb 7 14:30 /etc/localtime -> /usr/share/zoneinfo/Etc/UTC

Changing the Time Zone on Debian 13

Before changing the time zone, you need to find the long name of the time zone you want to use. Time zones use a “Region/City” format.

To list all available time zones, use the timedatectl command with the list-timezones option:

Terminal
timedatectl list-timezones
output
...
America/Montserrat
America/Nassau
America/New_York
America/Nipigon
America/Nome
...

To filter the list for a specific region or city, pipe the output through grep:

Terminal
timedatectl list-timezones | grep -i "europe"

Once you identify the correct time zone for your location, run the following command as root or user with sudo privileges :

Terminal
sudo timedatectl set-timezone <your_time_zone>

For example, to change the system’s time zone to Europe/London, you would run:

Terminal
sudo timedatectl set-timezone Europe/London

Verify the change by invoking the timedatectl command again:

Terminal
timedatectl
output
 Local time: Sat 2026-02-07 14:35:09 GMT
Universal time: Sat 2026-02-07 14:35:09 UTC
RTC time: Sat 2026-02-07 14:35:09
Time zone: Europe/London (GMT, +0000)
System clock synchronized: yes
systemd-timesyncd.service active: yes
RTC in local TZ: no

The time zone has been successfully changed.

Using dpkg-reconfigure

On Debian systems, you can also change the time zone using the tzdata package. This method provides an interactive text-based interface:

Terminal
sudo dpkg-reconfigure tzdata

The command opens a menu where you can select the geographic area and then the city or region. After making your selection, the system time zone is updated automatically.

Troubleshooting

Changes do not persist after reboot
Ensure /etc/localtime is a symlink to a valid file in /usr/share/zoneinfo and re-run sudo timedatectl set-timezone Region/City.

Clock is still wrong after changing the time zone
Check that NTP sync is active with timedatectl status. If it is disabled, enable time synchronization: sudo timedatectl set-ntp true.

FAQ

How do I check the current time zone on Debian 13?
Run the timedatectl command without any arguments. The “Time zone” line in the output shows the currently configured time zone.

Can I change the time zone without restarting?
Yes. The timedatectl set-timezone command takes effect immediately. There is no need to restart the system or any services.

What is the difference between timedatectl and dpkg-reconfigure tzdata?
Both methods achieve the same result. timedatectl is a single command that works on any systemd-based distribution. dpkg-reconfigure tzdata provides an interactive menu and is specific to Debian and Ubuntu systems.

Where are the time zone files stored?
Time zone data files are stored in the /usr/share/zoneinfo directory. The /etc/localtime file is a symlink that points to the active time zone file in that directory.

Conclusion

To change the time zone on Debian 13, use the sudo timedatectl set-timezone command followed by the long name of the time zone you want to set.

If you have any questions, feel free to leave a comment below.

Awk Cheatsheet

Basic Usage

Process lines and fields.

Command Description
awk '{print}' file.txt Print all lines
awk '{print $1}' file.txt Print first field
awk '{print $1, $3}' file.txt Print multiple fields
awk 'NR==1{print}' file.txt Print first line
awk 'NR>1{print}' file.txt Skip header

Field Separators

Change the input field separator.

Command Description
awk -F ':' '{print $1}' /etc/passwd Use colon separator
awk -F ',' '{print $2}' file.csv CSV column
awk -F '\t' '{print $1}' file.tsv TSV column
`awk ‘BEGIN{FS=" “} {print $2}’ file.txt`

Pattern Matching

Filter lines by conditions.

Command Description
awk '/error/ {print}' file.log Match regex
awk '$3 > 100 {print}' file.txt Numeric condition
awk '$1 == "root" {print}' /etc/passwd String match
awk 'NF == 3 {print}' file.txt Exact field count
awk 'NF > 0 {print}' file.txt Non-empty lines

Calculations

Do arithmetic and totals.

Command Description
awk '{sum += $2} END {print sum}' file.txt Sum column
awk '{sum += $2} END {print sum/NR}' file.txt Average column
awk 'BEGIN{print 5*7}' Simple calculation
awk '$2 > 0 {print $1, $2*1.2}' file.txt Multiply column

Output Formatting

Format output and columns.

Command Description
awk '{printf "%s\t%s\n", $1, $2}' file.txt Tab-separated output
awk '{printf "%-20s %s\n", $1, $2}' file.txt Left-align columns
awk '{printf "%.2f\n", $1}' file.txt Format numbers
awk 'BEGIN{OFS=","} {print $1,$2}' file.txt Set output separator

Common Options

Useful flags to remember.

Option Description
-F Set input field separator
-v Set variable (e.g., -v limit=10)
-f Read program from file
-E Use extended regex (gawk)
--posix POSIX mode

Grep Cheatsheet

Basic Search

Find matching lines in a file.

Command Description
grep "pattern" file.txt Search a single file
grep -i "pattern" file.txt Case-insensitive search
grep -n "pattern" file.txt Show line numbers
grep -v "pattern" file.txt Invert match
grep -w "word" file.txt Match whole words

Multiple Files

Search across multiple files.

Command Description
grep "pattern" file1 file2 Search specific files
grep "pattern" *.log Search by glob
grep -l "pattern" *.log Show matching filenames
grep -L "pattern" *.log Show non-matching filenames

Recursive Search

Search directories recursively.

Command Description
grep -r "pattern" dir/ Recursive search
grep -R "pattern" dir/ Follow symlinks
grep -r --include="*.conf" "pattern" dir/ Include file types
grep -r --exclude="*.log" "pattern" dir/ Exclude file types

Context Output

Show lines around matches.

Command Description
grep -C 3 "pattern" file.txt 3 lines before and after
grep -A 2 "pattern" file.txt 2 lines after
grep -B 2 "pattern" file.txt 2 lines before

Count and Only Matches

Summarize or extract matches.

Command Description
grep -c "pattern" file.txt Count matching lines
grep -o "pattern" file.txt Only the matching part
grep -m 1 "pattern" file.txt Stop after 1 match

Extended Regex

Use more powerful patterns.

Command Description
[`grep -E “foo bar” file.txt`](/post/grep-multiple-patterns/)
grep -E "colou?r" file.txt Optional character
grep -E "[0-9]{3}" file.txt Repetition
grep -E "^start" file.txt Line starts with
grep -E "end$" file.txt Line ends with

Common Options

Useful flags to remember.

Option Description
-i Ignore case
-n Show line numbers
-v Invert match
-w Match whole words
-r Recursive search
-E Extended regex
-F Fixed strings (no regex)
-H Always show filename
-q Quiet mode (exit status only)
❌
❌