Linux commands

Linux commands

Here are some important Linux commands that are widely used for file management, system navigation, user management, and system administration:

1. File and Directory Management

  • ls: Lists files and directories in the current directory.

    • Example: ls -l (detailed list), ls -a (includes hidden files)
  • cd: Changes the current directory.

    • Example: cd /home/user (navigate to /home/user)
  • pwd: Prints the current working directory.

    • Example: pwd
  • mkdir: Creates a new directory.

    • Example: mkdir new_directory
  • rmdir: Removes an empty directory.

    • Example: rmdir empty_directory
  • rm: Removes files or directories.

    • Example: rm file.txt, rm -r directory_name (removes directory with content)
  • cp: Copies files or directories.

    • Example: cp file1.txt file2.txt, cp -r dir1 dir2
  • mv: Moves or renames files or directories.

    • Example: mv oldname.txt newname.txt
  • touch: Creates an empty file or updates file timestamp.

    • Example: touch file.txt
  • cat: Displays content of a file.

    • Example: cat file.txt
  • nano, vim: Opens file in text editors.

    • Example: nano file.txt, vim file.txt
  • find: Finds files and directories.

    • Example: find / -name filename.txt
  • grep: Searches for patterns within files.

    • Example: grep 'pattern' file.txt, grep -r 'pattern' /path/to/directory

2. File Permissions and Ownership

  • chmod: Changes file permissions.

    • Example: chmod 755 file.txt, chmod u+x script.sh
  • chown: Changes file ownership.

    • Example: chown user:group file.txt
  • chgrp: Changes the group ownership of a file.

    • Example: chgrp groupname file.txt

3. Process Management

  • ps: Displays currently running processes.

    • Example: ps aux, ps -ef
  • top: Displays real-time system processes and resource usage.

  • kill: Terminates a process by its process ID (PID).

    • Example: kill 12345, kill -9 12345 (force kill)
  • pkill: Terminates processes by name.

    • Example: pkill firefox
  • bg / fg: Sends jobs to background (bg) or foreground (fg).

4. Disk and System Information

  • df: Displays disk space usage.

    • Example: df -h
  • du: Shows the size of files and directories.

    • Example: du -sh directory_name
  • free: Displays memory usage.

    • Example: free -h
  • uname: Displays system information.

    • Example: uname -a
  • uptime: Shows how long the system has been running.

  • dmesg: Prints kernel and boot messages.

  • who: Shows who is logged in.

  • w: Displays system uptime and logged-in users.

5. Networking

  • ifconfig: Displays network interfaces and IP addresses.

    • Example: ifconfig eth0
  • ping: Sends ICMP echo request to a host.

  • netstat: Displays network connections, routing tables, and interface statistics.

  • ssh: Securely connects to a remote machine.

    • Example: ssh user@hostname
  • scp: Copies files between local and remote systems.

    • Example: scp file.txt user@remote:/path/to/destination
  • wget / curl: Downloads files from the web.

  • ip: Shows/manages network configurations.

    • Example: ip a, ip link show

6. User Management

  • useradd: Adds a new user.

    • Example: sudo useradd username
  • passwd: Changes the password for a user.

    • Example: passwd username
  • usermod: Modifies an existing user account.

    • Example: usermod -aG sudo username (add user to sudo group)
  • userdel: Deletes a user account.

    • Example: userdel username
  • groupadd: Creates a new group.

    • Example: groupadd groupname
  • groups: Displays group memberships of a user.

    • Example: groups username

7. Archiving and Compression

  • tar: Archives files into a tarball (optionally compressed with gzip or bzip2).

    • Example: tar -cvf archive.tar file1 file2, tar -xvf archive.tar

    • Example with compression: tar -czvf archive.tar.gz directory/

  • gzip: Compresses files.

    • Example: gzip file.txt, gunzip file.txt.gz
  • zip / unzip: Compresses and extracts ZIP archives.

8. Package Management (Depends on the Distribution)

  • For Debian/Ubuntu-based systems:

    • apt-get install: Installs a package.

      • Example: sudo apt-get install package_name
    • apt-get update: Updates the package index.

      • Example: sudo apt-get update
    • apt-get upgrade: Upgrades installed packages.

      • Example: sudo apt-get upgrade
  • For Red Hat/CentOS-based systems:

    • yum install: Installs a package.

      • Example: sudo yum install package_name
    • yum update: Updates the package index and upgrades packages.

      • Example: sudo yum update

9. System Monitoring

  • htop: Interactive process viewer.

  • iostat: Reports CPU, disk I/O, and network usage.

  • vmstat: Reports virtual memory statistics.

  • sar: Collects and reports system activity.

10. Shutdown/Restart

  • shutdown: Shuts down or reboots the system.

    • Example: shutdown -h now (shutdown), shutdown -r now (reboot)
  • reboot: Reboots the system immediately.

    • Example: sudo reboot
  • halt: Halts the system immediately.

    • Example: sudo halt

11. Advanced File Operations

  • stat: Displays detailed information about a file or file system.

    • Example: stat file.txt
  • ln: Creates hard or symbolic links to files.

    • Example: ln file.txt link_to_file.txt (hard link), ln -s file.txt symlink.txt (symbolic link)
  • basename / dirname: Extracts filename or directory path from a given path.

    • Example: basename /home/user/file.txt (outputs file.txt)

    • Example: dirname /home/user/file.txt (outputs /home/user)

12. Disk and Partition Management

  • fdisk: Used to view and manage disk partitions.

    • Example: fdisk /dev/sda
  • parted: Another tool for partition management, especially for large disks.

    • Example: parted /dev/sda
  • mkfs: Formats a partition with a specified filesystem.

    • Example: mkfs.ext4 /dev/sda1
  • mount / umount: Mounts or unmounts a file system.

    • Example: mount /dev/sda1 /mnt, umount /mnt
  • blkid: Shows UUIDs and details about block devices.

    • Example: blkid /dev/sda1
  • lsblk: Lists information about block devices (disks and partitions).

    • Example: lsblk
  • df -i: Shows inode usage on filesystems (useful when df shows space available but file creation fails due to lack of inodes).

13. System Resource and Performance Monitoring

  • iotop: Displays real-time disk I/O usage.

    • Example: sudo iotop
  • strace: Traces system calls and signals used by a command.

    • Example: strace -p <PID>, strace ls
  • lsof: Lists open files and the processes that opened them (useful for checking which files are in use).

    • Example: lsof | grep filename, lsof -i :80 (lists processes using port 80)
  • ncdu: Disk usage analyzer, an easy-to-read alternative to du.

    • Example: ncdu /home
  • sysctl: Views or modifies kernel parameters.

    • Example: sysctl -a (shows all kernel parameters), sysctl vm.swappiness=10 (changes swappiness parameter)
  • watch: Runs a command repeatedly at regular intervals and displays the output.

    • Example: watch -n 5 df -h (runs df -h every 5 seconds)

14. Networking and Internet Tools

  • traceroute: Tracks the route packets take to a network host.

  • nc (netcat): Reads and writes data across network connections (a Swiss-army knife for network-related tasks).

    • Example: nc -l 12345 (listens on port 12345), nc google.com 80 (connects to google on port 80)
  • dig: DNS lookup utility (more advanced than nslookup).

  • hostname: Shows or sets the system's hostname.

    • Example: hostname, hostnamectl set-hostname newhostname
  • arp: Shows the system's ARP (Address Resolution Protocol) table.

    • Example: arp -a
  • ss: Displays socket statistics, more modern than netstat.

    • Example: ss -tuln (shows open ports and services)

15. System Logs and Debugging

  • journalctl: Views system logs on systemd systems.

    • Example: journalctl -xe (view recent logs with errors), journalctl -b (view logs since last boot)
  • tail: Displays the last lines of a file (often used for logs).

    • Example: tail -f /var/log/syslog (live view of log file)
  • dstat: Combines the functionality of vmstat, iostat, and netstat in real-time.

    • Example: dstat
  • last: Shows the login history of users.

    • Example: last
  • logrotate: Rotates, compresses, and removes old logs automatically (usually run in cron jobs).

16. Scripting and Automation

  • cron: Schedules tasks to run periodically (using crontab).

    • Example: crontab -e (edit user crontab), crontab -l (list cron jobs)
  • at: Schedules a task to run at a specific time (only once).

    • Example: echo "shutdown -h now" | at 22:00
  • alias: Creates shortcuts for long commands.

    • Example: alias ll='ls -lah'
  • export: Exports an environment variable.

    • Example: export PATH=$PATH:/usr/local/bin
  • source: Executes commands from a file in the current shell.

    • Example: source ~/.bashrc
  • awk: A powerful text processing tool for extracting and manipulating text.

    • Example: awk '{print $1}' file.txt
  • sed: Stream editor for filtering and transforming text.

    • Example: sed 's/oldtext/newtext/g' file.txt

17. Security and Permissions

  • sudo: Runs a command as the superuser (root).

    • Example: sudo apt-get update
  • su: Switches to another user.

    • Example: su - username
  • umask: Sets default permissions for newly created files and directories.

    • Example: umask 022
  • setfacl / getfacl: Manages Access Control Lists (ACLs) for fine-grained file permissions.

    • Example: setfacl -m u:username:rwx file.txt, getfacl file.txt

18. Backup and Recovery

  • rsync: Synchronizes files and directories between two locations efficiently.

    • Example: rsync -avh /source/ /destination/
  • dd: Copies and converts files at a low level, often used for backups or disk cloning.

    • Example: dd if=/dev/sda of=/path/to/backup.img bs=64K
  • fsck: Checks and repairs file system consistency.

    • Example: fsck /dev/sda1

19. Virtualization and Containers

  • docker: Manages containerized applications.

    • Example: docker run -it ubuntu bash, docker ps (list running containers)
  • virt-install: Installs virtual machines via command line (for libvirt/KVM).

    • Example: virt-install --name vm1 --ram 1024 --vcpus 1 --disk path=/var/lib/libvirt/images/vm1.img,size=10
  • vagrant: Automates the setup of virtualized development environments.

    • Example: vagrant up, vagrant ssh

20. System Control and Administration

  • systemctl: Manages systemd services (starting, stopping, enabling, disabling services).

    • Example: systemctl start apache2, systemctl enable apache2, systemctl status apache2
  • timedatectl: Configures date, time, and timezone settings.

    • Example: timedatectl set-timezone America/New_York
  • hostnamectl: Changes the system hostname and related settings.

    • Example: hostnamectl set-hostname newhostname
  • modprobe: Loads or unloads kernel modules.

    • Example: modprobe module_name
  • sysfs: Interacts with system hardware information exposed through /sys.

    • Example: cat /sys/class/net/eth0/speed

21. Networking Tools

  • mtr: Combines the functionality of traceroute and ping to diagnose network issues.

  • iftop: Displays bandwidth usage by network interface.

    • Example: sudo iftop -i eth0
  • tcpdump: Captures and analyzes network packets.

    • Example: sudo tcpdump -i eth0, tcpdump port 80
  • iptraf-ng: An interactive, real-time network monitoring utility.

  • ethtool: Displays or changes network interface card (NIC) settings.

    • Example: sudo ethtool eth0
  • ufw: Manages uncomplicated firewall settings (commonly used in Ubuntu).

    • Example: sudo ufw allow 22, sudo ufw enable
  • firewalld: Firewall management tool used in RedHat/CentOS.

    • Example: sudo firewall-cmd --permanent --add-port=8080/tcp

22. Filesystem and Storage Management

  • lsattr: Lists attributes of files and directories.

    • Example: lsattr file.txt
  • chattr: Changes file attributes, for example, to make a file immutable.

    • Example: chattr +i file.txt
  • xfs_admin: Manages XFS file systems (resizing, repairing, etc.).

    • Example: xfs_admin -L new_label /dev/sda1
  • quota: Displays disk quotas and user limits on filesystems.

    • Example: quota -u username
  • lvm: Logical Volume Manager commands like lvcreate, vgextend, etc.

    • Example: lvcreate -L 10G -n lv_data vg1, lvextend -L +5G /dev/vg1/lv_data
  • cryptsetup: Sets up encrypted filesystems using LUKS (Linux Unified Key Setup).

    • Example: cryptsetup luksFormat /dev/sda1, cryptsetup luksOpen /dev/sda1 secure_drive

23. Development and Debugging Tools

  • gdb: GNU Debugger, used for debugging programs.

    • Example: gdb ./program, gdb --pid=<PID>
  • objdump: Displays detailed information about binary files.

    • Example: objdump -d binary_file
  • ldd: Displays shared library dependencies for executable files.

    • Example: ldd /bin/ls
  • valgrind: A tool for memory debugging, memory leak detection, and profiling.

    • Example: valgrind ./program
  • nm: Displays symbols from object files.

    • Example: nm a.out
  • strace: Tracks system calls and signals a process makes.

    • Example: strace -p <PID>

24. Package Management Tools

  • dpkg: Low-level package management for Debian-based distributions (like Ubuntu).

    • Example: dpkg -i package.deb, dpkg -l (list installed packages)
  • rpm: Low-level package management for Red Hat-based distributions.

    • Example: rpm -ivh package.rpm, rpm -qa (list installed packages)
  • yum: High-level package manager for Red Hat/CentOS (predecessor of dnf).

    • Example: yum search package_name, yum remove package_name
  • dnf: Modern package manager for Red Hat/CentOS/Fedora.

    • Example: dnf install package_name, dnf update
  • snap: Manages snap packages, often used for containerized applications.

    • Example: snap install package_name, snap list
  • flatpak: Another framework for distributing desktop applications in containers.

    • Example: flatpak install package_name

25. Containers and Virtualization

  • virsh: CLI interface for managing virtual machines using libvirt.

    • Example: virsh list --all, virsh start vm1
  • kvm: Manages kernel-based virtual machines.

    • Example: kvm -hda disk.img -m 512 -net nic -net user
  • docker-compose: Manages multi-container Docker applications using YAML configuration files.

    • Example: docker-compose up, docker-compose down
  • podman: A daemonless container engine that is compatible with Docker.

    • Example: podman run -it fedora, podman ps
  • lxc: Linux Containers toolset, alternative to Docker for containerization.

    • Example: lxc-create -n container -t download, lxc-start -n container

26. Performance Monitoring

  • perf: Performance analysis tool for Linux, particularly useful for kernel developers.

    • Example: perf top, perf record -a
  • sar: Collects and reports system activity information.

    • Example: sar -u 1 3 (CPU utilization over 1-second intervals)
  • iotop: Real-time disk I/O monitoring by process.

    • Example: iotop
  • latencytop: Identifies latency issues in your system.

  • dstat: A versatile resource monitoring tool that combines features of vmstat, iostat, and netstat.

    • Example: dstat --cpu --io --net

27. Security and Cryptography

  • fail2ban: Protects your server from brute-force attacks by blocking IP addresses.

    • Example: sudo fail2ban-client status, sudo fail2ban-client set sshd banip <IP>
  • gpg: GNU Privacy Guard for encrypting and signing files or messages.

    • Example: gpg --gen-key, gpg -e -r recipient file.txt
  • openssl: Toolset for SSL/TLS, certificates, and cryptography functions.

    • Example: openssl genpkey -algorithm RSA -out private.pem
  • nmap: A powerful network scanning tool for security auditing and network exploration.

    • Example: nmap -A 192.168.1.1

28. Miscellaneous

  • tldr: Displays simplified and practical examples of common commands.

    • Example: tldr tar
  • bc: A command-line calculator supporting floating-point arithmetic.

    • Example: echo "scale=2; 10/3" | bc
  • yes: Continuously outputs a string until terminated.

    • Example: yes "I agree"
  • shuf: Generates random permutations from input lines.

    • Example: shuf -n 1 file.txt (outputs a random line from a file)
  • units: Converts between different units of measurement.

    • Example: units '10 miles' 'kilometers'
  • tree: Displays a directory structure in a tree-like format.

    • Example: tree /path/to/directory
  • alias: Defines a shortcut for a command.

    • Example: alias ll='ls -la'

30. Specialized File Management Commands

  • split: Splits a file into smaller chunks.

    • Example: split -b 100M largefile.bin part_ (splits a file into 100 MB chunks)
  • shred: Securely deletes a file by overwriting it multiple times.

    • Example: shred -u file.txt
  • rev: Reverses the characters in each line of a file.

    • Example: echo "hello" | rev (outputs olleh)
  • rename: Renames multiple files using a regular expression.

    • Example: rename 's/\.txt$/.bak/' *.txt (renames .txt files to .bak)
  • xxd: Converts a file to hexadecimal and back.

    • Example: xxd file.txt, xxd -r file.hex

31. Advanced Scripting and Text Processing

  • xargs: Constructs argument lists and passes them to a command.

    • Example: find . -name '*.txt' | xargs rm (removes all .txt files)
  • tee: Reads from standard input and writes to both standard output and a file.

    • Example: echo "hello" | tee output.txt (writes "hello" to both terminal and file)
  • paste: Merges lines of files horizontally.

    • Example: paste file1.txt file2.txt (merges lines from both files side-by-side)
  • comm: Compares two sorted files line by line.

    • Example: comm file1.txt file2.txt
  • tac: Displays the contents of a file in reverse order (last line first).

    • Example: tac file.txt
  • expr: Evaluates expressions (useful in shell scripts for arithmetic).

    • Example: expr 1 + 2
  • bc: Command-line calculator.

    • Example: echo "2^10" | bc
  • tr: Translates or deletes characters in input.

    • Example: echo "HELLO" | tr 'A-Z' 'a-z' (converts to lowercase)

32. Terminal Utilities and Shortcuts

  • tmux: Terminal multiplexer to manage multiple terminal sessions.

    • Example: tmux (starts a new session), tmux attach (reattaches to an existing session)
  • screen: Another terminal multiplexer, similar to tmux.

    • Example: screen (starts a new session), screen -r (reattaches to a session)
  • reset: Resets the terminal display and clears any weird states.

    • Example: reset
  • script: Records a terminal session to a file.

    • Example: script session.txt
  • yes: Repeats a string until terminated.

    • Example: yes "agree" (repeats "agree" until stopped with Ctrl+C)

33. System Monitoring and Information

  • lsmod: Lists loaded kernel modules.

    • Example: lsmod
  • uptime: Displays system uptime and load averages.

    • Example: uptime
  • lshw: Lists detailed hardware information.

    • Example: sudo lshw
  • inxi: Displays detailed system information (including CPU, GPU, RAM, etc.).

    • Example: inxi -Fx
  • acpi: Displays battery status and thermal information (useful for laptops).

    • Example: acpi -b
  • lsof: Lists open files and processes using them.

    • Example: lsof /dev/sda1
  • dmesg: Displays kernel-related messages (especially useful for debugging hardware issues).

    • Example: dmesg | grep error
  • vmstat: Reports virtual memory, process, and CPU activity.

    • Example: vmstat 5 (reports every 5 seconds)
  • watch: Executes a command repeatedly and displays the output.

    • Example: watch -n 2 df -h (runs df -h every 2 seconds)

34. Networking and Connectivity Tools

  • whois: Queries domain registration information.

  • host: Performs DNS lookups.

  • iwconfig: Configures wireless network interfaces (similar to ifconfig but for wireless).

    • Example: iwconfig wlan0
  • w: Displays who is logged into the system and their activities.

    • Example: w
  • ip addr: Shows detailed network interface information (replacement for ifconfig).

    • Example: ip addr show
  • ip route: Manages routing tables.

    • Example: ip route add 192.168.1.0/24 via 192.168.0.1

35. Process and System Control

  • pkill: Sends a signal to a process by its name (alternative to kill).

    • Example: pkill firefox
  • renice: Alters the scheduling priority of a running process.

    • Example: renice +5 -p <PID>
  • fg: Brings a background process to the foreground.

    • Example: fg %1 (brings job 1 to the foreground)
  • bg: Resumes a suspended job in the background.

    • Example: bg %1 (resumes job 1 in the background)

36. User and Group Management

  • groups: Shows the groups a user is part of.

    • Example: groups username
  • useradd: Adds a new user.

    • Example: sudo useradd -m username
  • usermod: Modifies a user account.

    • Example: usermod -aG sudo username
  • passwd: Changes a user's password.

    • Example: passwd username
  • chage: Changes user password expiration information.

    • Example: sudo chage -l username

37. System Maintenance and Troubleshooting

  • fsck: Checks and repairs file system inconsistencies.

    • Example: fsck /dev/sda1
  • badblocks: Searches for bad sectors on a disk.

    • Example: sudo badblocks -v /dev/sda1
  • smartctl: Monitors the health of hard drives and SSDs via S.M.A.R.T.

    • Example: sudo smartctl -a /dev/sda
  • iotop: Displays disk I/O usage by processes in real time.

    • Example: iotop

38. Archiving and Compression

  • tar: Archive files into a tarball or extract files.

    • Example: tar -czvf archive.tar.gz folder/, tar -xvzf archive.tar.gz
  • gzip: Compresses or decompresses files.

    • Example: gzip file.txt, gunzip file.txt.gz
  • bzip2: Compresses files using the Burrows-Wheeler block-sorting text compression algorithm.

    • Example: bzip2 file.txt
  • xz: Compresses files with higher compression than gzip or bzip2.

    • Example: xz file.txt
  • unzip: Extracts files from a ZIP archive.

39. Date and Time

  • date: Displays or sets the system date and time.

    • Example: date, date --set="2024-10-11 10:30"
  • cal: Displays a calendar.

    • Example: cal
  • ntpq: Monitors NTP daemon and shows the status of time synchronization.

    • Example: ntpq -p

40. Miscellaneous Useful Commands

  • flock: Manages file locking in shell scripts.

    • Example: flock /tmp/mylockfile command
  • chroot: Changes the root directory for a process (used for system recovery and containers).

    • Example: chroot /mnt/recovery /bin/bash
  • ncdu: Disk usage analyzer with a text-based user interface (faster alternative to du).

    • Example: ncdu /home
  • hexdump: Displays file contents in hexadecimal, decimal

  • uptime: Displays system uptime, load averages, and number of users logged in.

    • Example: uptime
  • alias: Creates a shortcut for a command.

    • Example: alias ll='ls -la'
  • bc: A command-line calculator.

    • Example: echo "5 * 7" | bc
  • env: Displays environment variables.

    • Example: env