Top 40 Useful Linux Command Snippets

Linux Command Snippets

Linux is a powerful and flexible operating system widely used for its stability, security, and efficiency in server environments. Mastering the Linux command line can significantly enhance productivity by allowing users to interact directly with the system through commands and scripts. Whether you’re managing servers, troubleshooting issues, or performing routine tasks, knowing a variety of useful Linux commands is essential.

This guide provides a collection of common Linux command snippets, organized by task, that will help you efficiently manage files, processes, services, and more.

1. Checking Disk Usage with `df` and `du`

Efficient disk space management is crucial. These commands help monitor available disk space and identify large files or directories.

df: Displays the amount of disk space used and available on mounted filesystems.
Example: df -h (Shows human-readable output in MB/GB)

df command

du: Estimates file and directory space usage.
Example: du -sh /path/to/directory (Displays summary in human-readable format)

du command

2. Viewing Active Processes with `top` and `htop`

Monitoring system performance is key. Use these tools to view real-time information about running processes and resource usage.

top: Displays real-time information on system processes, CPU usage, memory, and load averages.
Example: top

Top command

htop: An interactive, more user-friendly process viewer.
Example: htop (You may need to install it: `sudo apt install htop`)

htop command

3. Monitoring Memory Usage with `free`

Check system memory availability and usage, which is essential for maintaining optimal performance, especially on busy servers.

free: Displays the amount of free and used memory in the system.
Example: free -h (Shows memory usage in human-readable format)

Free Command

4. Finding Files with `find` and `locate`

Easily locate files on the system using powerful search utilities. `find` is versatile but slower, while `locate` provides quicker results.

find: Searches for files in a directory hierarchy.
Example: find /path/to/directory -name “filename.txt”

Find Command

locate: Uses a database to quickly find files by name (faster than `find` but requires updatedb).
Example: locate filename.txt

5. Compressing and Extracting Files with `tar` and `gzip`

Archive and compress files to save disk space or to prepare files for transfer. These commands are key for handling backups or distributions.

tar: Archiving utility.
Example: tar -cvf archive.tar /path/to/directory (Create a tar archive)
Example: tar -xvf archive.tar (Extract tar archive)

gzip: Compresses files.
Example: gzip filename.txt
Example: gunzip filename.txt.gz (Uncompress file)

6. Managing Services with `systemctl`

Start, stop, and manage services on your system. This command is fundamental for service management in most modern Linux distributions.

systemctl: Used to manage system services (start, stop, restart, and enable services at boot).
Example: systemctl start service_name
Example: systemctl enable service_name
Example: systemctl status service_name

Service Command

7. Checking System Uptime

Quickly see how long your system has been running since the last reboot, useful for assessing server reliability or troubleshooting.

uptime: Displays the system’s uptime (time since the last reboot), load averages, and the current time.
Example: uptime

Uptime Command

8. Changing File Permissions with `chmod`

Control access to files and directories by adjusting user permissions, ensuring security and proper file access management.

chmod: Changes the permissions of a file or directory.
Example: chmod 777 filename (Set read/write/execute permissions for owner and read/execute for others)
Symbolic format: chmod u=rwx,g=rx,o=rx filename

Chmod Command

9. Changing File Ownership with `chown`

Set or change file and directory ownership to the correct users or groups to manage access control efficiently.

chown: Changes the ownership of a file or directory.
Example: chown username:groupname filename

10. Killing Processes by PID

Terminate unresponsive or resource-hogging processes directly by using their process ID (PID) to maintain system stability.

kill: Sends a signal to terminate processes by PID (Process ID).
Example: kill 12345 (Terminates process with PID 12345)
Force terminate: kill -9 12345

Kill Command

11. Viewing Log Files with `tail`, `less`, and `cat`

System logs provide critical insight into how services and applications are running. These commands are essential for log monitoring.

tail: Displays the last lines of a file (commonly used with logs).
Example: tail -f /var/log/auth.log (Continuously outputs new log entries)

Tail Command

less: Displays file contents one page at a time.
Example: less /var/log/auth.log

Less Command

cat: Outputs the content of a file to the terminal.
Example: cat /var/log/auth.log

Cat Command

12. Network Diagnostics with `ping`, `netstat`, and `traceroute`

Diagnose and troubleshoot network connectivity issues with these common tools, crucial for maintaining network stability.

ping: Tests network connectivity to a host.
Example: ping techhyme.com

Ping Command

netstat: Displays network connections, routing tables, and interface statistics.
Example: netstat -tuln (Shows listening ports)

Netstat Command

traceroute: Displays the route packets take to a network host.
Example: traceroute techhyme.com

Traceroute Command

13. Creating Symbolic Links with `ln`

Symbolic links make it easier to access files from multiple locations without duplicating the actual data.

ln: Creates hard or symbolic links between files.
Example: ln -s /path/to/file /path/to/symlink

14. Listing Open Files with `lsof`

View which files are in use by processes, an invaluable tool for troubleshooting locked files or resource conflicts.

lsof: Lists open files and the processes using them.
Example: lsof -i :80 (Lists processes using port 80)

lsof Command

15. Managing Users with `useradd`, `usermod`, and `userdel`

These commands allow you to create, modify, and delete user accounts, vital for maintaining system security and proper user management.

useradd: Adds a new user.
Example: sudo useradd username

Useradd Command

usermod: Modifies user account settings.
Example: sudo usermod -aG sudo username (Adds user to the sudo group)

userdel: Deletes a user.
Example: sudo userdel username

16. Checking Linux Kernel Version

Knowing the current kernel version can help with compatibility checks and debugging hardware or software issues.

uname: Displays kernel information.
Example: uname -r (Displays the kernel version)

Uname Command

17. Scheduling Tasks with `cron`

Automate repetitive tasks by scheduling them to run at specified intervals, essential for regular maintenance and backups.

cron: Schedules tasks to run at regular intervals.
Example: crontab -e (Opens crontab to edit scheduled tasks)
Example: 0 5 /path/to/script.sh (Runs the script every day at 5:00 AM)

Crontab Command

18. Downloading Files with `wget` and `curl`

Download and transfer files directly from the command line. These commands are useful for downloading packages, files, or data from the internet.

wget: Downloads files from the web.
Example: wget http://example.com/file.zip

curl: Transfers data from or to a server.
Example: curl -O http://example.com/file.zip

Curl Command

19. Mounting and Unmounting Drives

Attach and detach file systems manually using these commands, necessary for managing storage devices and partitions.

mount: Mounts a filesystem.
Example: mount /dev/sda1 /mnt

umount: Unmounts a filesystem.
Example: umount /mnt

20. Copying Files and Directories with `cp` and `rsync`

Move or copy files efficiently, whether locally or over a network, and ensure data is securely transferred between systems.

cp: Copies files and directories.
Example: cp file.txt /path/to/destination/

rsync: Efficiently syncs files between locations.
Example: rsync -av /source/ /destination/

21. Searching Inside Files with `grep`

Quickly search for specific patterns within files, especially useful when analyzing large logs or configuration files.

grep: Searches for patterns within files.
Example: grep “error” /var/log/syslog

Grep Command

22. Using SSH for Remote Access

Securely connect to remote systems over a network, enabling remote management and file transfer across systems.

ssh: Connects to a remote system via SSH.
Example: ssh user@remote_host

23. Checking Open Ports with `ss`

Monitor network sockets to view which ports are open, critical for security auditing and network diagnostics.

ss: Displays network socket information.
Example: ss -tuln (Shows listening ports)

ss Command

24. Editing Text Files with `vim` and `nano`

Use these text editors to make quick changes to configuration files or scripts directly from the terminal.

vim: A powerful text editor.
Example: vim filename

nano: A simple, easy-to-use text editor.
Example: nano filename

25. Viewing and Configuring Network Interfaces with `ifconfig` and `ip`

Check and configure network interfaces to ensure proper connectivity and address management.

ifconfig: Displays network interface information.
Example: ifconfig

ifconfig Command

ip: Replaces ifconfig to manage network interfaces.
Example: ip a (Shows all network interfaces)

ip command

26. Monitoring Disk I/O with `iostat`

Analyze disk input/output to identify bottlenecks and troubleshoot performance issues related to storage.

iostat: Monitors system I/O device loading.
Example: iostat

iostat Command

27. Checking Hardware Info with `lscpu` and `lsblk`

View detailed information about the system’s CPU, memory, and block devices to ensure hardware is functioning correctly.

lscpu: Displays CPU architecture information.
Example: lscpu

lscpu command

lsblk: Lists information about block devices.
Example: lsblk

lsblk Command

28. Managing Partitions with `fdisk` and `parted`

Partition your disks efficiently, ensuring that your file systems are correctly structured and optimized for performance.

fdisk: A disk partitioning tool.
Example: fdisk /dev/sda

Fdisk Command

parted: Another partitioning tool, useful for working with large drives.
Example: parted /dev/sda

29. Tracking System Resource Usage with `vmstat`

Keep track of system resources such as CPU, memory, and disk usage over time for performance monitoring.

vmstat: Reports virtual memory statistics.
Example: vmstat 5 (Reports every 5 seconds)

vmstat Command

30. Creating and Managing Shell Scripts

Automate tasks and create complex workflows by writing shell scripts, a fundamental skill for any Linux user or system administrator.

Shell scripts: Automate tasks by creating .sh files.
Example: #!/bin/bash echo “Hello, World!”

31. Archiving and Encrypting Files with `gpg`

Securely encrypt, sign, and verify files using GNU Privacy Guard (GPG) to ensure data integrity and confidentiality.

gpg: Encrypts and signs data.
Example: gpg -c filename (Encrypts a file)
Example: gpg filename.gpg (Decrypts a file)

gpg command

32. Checking Installed Packages with `dpkg` or `rpm`

Easily check for installed software packages and ensure systems have the necessary tools and applications.

dpkg: Package manager for Debian-based systems.
Example: dpkg -l (Lists installed packages)

Dpkg Command

rpm: Package manager for Red Hat-based systems.
Example: rpm -qa (Lists installed packages)

33. Redirecting Output with `>`, `>>`, and `|`

Direct command output to files or chain commands together using pipes, essential for working efficiently with multiple tools.

>: Redirects output to a file (overwrites the file).
Example: echo “text” > file.txt

Echo Command

>>: Appends output to a file.
Example: echo “more text” >> file.txt

|: Pipes output from one command to another.
Example: cat file.txt | grep “pattern”

34. Enabling and Disabling Swap Space

Manage swap space to optimize memory usage, particularly useful for servers with limited physical memory.

swapon: Enables swap space.
Example: swapon /swapfile

swapoff: Disables swap space.
Example: swapoff /swapfile

35. Searching Package Repositories with `apt`, `yum`, and `dnf`

Search and manage software packages from the repository to install or update applications on your system.

apt: For Debian/Ubuntu-based systems.
Example: apt search package_name

APT Search Command

yum: For CentOS/RHEL systems.
Example: yum search package_name

dnf: For Fedora-based systems.
Example: dnf search package_name

36. Checking IP Address with `hostnamectl`

Display the current hostname, system information, and IP address for system identification.

hostnamectl: Shows or sets the system hostname.
Example: hostnamectl

hostnamectl Command

37. Managing Firewalls with `ufw` or `iptables`

Configure firewalls to secure your system against unauthorized access, vital for network security.

ufw: Uncomplicated Firewall interface.
Example: ufw allow 22 (Allow SSH)

iptables: More advanced firewall management.
Example: iptables -A INPUT -p tcp –dport 22 -j ACCEPT

38. Viewing System Boot Logs with `dmesg`

Inspect boot messages and hardware diagnostics to troubleshoot system startup issues.

dmesg: Prints the kernel ring buffer.
Example: dmesg | less (View boot logs)

39. Listing Recently Modified Files

Find recently modified files in a directory for auditing or debugging purposes.

find: Find files modified in the last n days.
Example: find /path -mtime -1 (Find files modified in the last 1 day)

40. Setting Environment Variables

Configure environment variables to set system-wide or session-specific options, crucial for managing software environments.

export: Temporarily sets environment variables.
Example: export VAR_NAME=value
/etc/environment: For permanent environment variable settings.

This collection provides a well-rounded set of Linux commands and snippets, each designed to help you perform essential tasks in system administration, file management, network configuration, and more.

Whether you’re a beginner or an experienced user, these tools will enhance your command-line productivity.

You may also like:

Related Posts

Leave a Reply