Linux is a robust, open-source operating system that has become a cornerstone in various computing environments, from personal desktops to enterprise servers. Developed collaboratively by thousands of programmers worldwide, Linux offers a flexible and secure platform that can be tailored to meet diverse needs. Its open-source nature allows users to access the source code, modify it, and distribute their versions, fostering innovation and customization.
This article covers key Linux commands across various categories, including basic navigation, file management, system administration, networking, package management, advanced operations, and customization. Each command is explained with practical examples to help users understand their applications and benefits. The aim is to equip readers with the knowledge to enhance their command-line skills and improve their efficiency in managing Linux systems.
The terminal’s ongoing relevance in a GUI world
Mastering the command line interface (CLI) is essential for Linux users, as it provides unparalleled control and efficiency. The CLI enables users to perform complex tasks with simple commands, automate processes, and troubleshoot issues effectively.
Unlike graphical interfaces, the CLI offers a more direct and scriptable interaction with the system, which is crucial for system administrators and developers who require precision and speed in their workflows. Even in day-to-day human-CLI interactions, one can often substitute several minutes of clicking through apps with a well-crafted command line invocation and even batch jobs easily that way.
Basic Linux commands
Some operator’s notes:
- Absolute vs relative paths: In Linux’s Absolute paths always start with / and always point to a specific folder or file in your filesystem; relative paths do not start in a / and are always relative to one’s current working directory.
- Filesystems & filenames are case sensitive: For instance, /home/user, /home/User, & /home/USER are three different folders.
- If you get lost: pwd prints the current working directory. (Technically, echoes the output of the PWD environment variable to STDOUT, unless directed elsewhere.)
- To clear your workspace: Pressing Ctrl+L in the terminal will clear your screen while preserving the command you may or may not be typing already. In case eg. a previous command’s output garbled your terminal.
- Need more help?: Linux’s manual can help. Just run “man [command]”, eg. man unzip – or search by keyword with “man -k [keyword]”, for example man -k firewall will list all the manual pages that mention firewalls. Go ahead – each and every command below has much more functionality to discover.
Navigational commands (e.g., cd, ls, pwd):
Navigational commands are fundamental for moving through the Linux filesystem.
- cd: Changes the current directory: All the filesystems attached to a Linux system are attached (mounted onto) a single unified directory tree, so cd can also change in which mounted storage device (aka “block device”) you’re currently working. (See pwd)
- cd [folder] eg. cd /home/user/Documents changes your current working directory to the user’s Documents directory from wherever you were previously in your system due to the usage of absolute vs relative paths; eg. cd Documents/ would also work, provided your current working directory is /home/user/.
- cd (without parameters) or cd ~ always returns you to the current user’s $HOME directory (typically /home/user/). In Bash, ~ (tilde) equals the current user’s HOME environment variable.
- cd – (dash/hyphen) returns you to your last used (most recent) working directory before changing to the current one.
- ls: Lists directory contents.
- ls -l displays detailed information about files & directories.
- ls -lart displays detailed information about all files & directories (including hidden/system) sorted by time in reverse order (ie. from oldest to newest)
File management commands (e.g., cp, mv, rm, touch):
File management commands are essential for handling files & directories.
- cp: Copies files or directories.
- cp file1.txt /backups/ copies file1.txt to the /backups directory.
- cp -vR directory1/ /path/to/target/ recursively copies directory1 (a subdirectory of the current working directory) to the absolute path /path/to/target/directory1. The -v switch makes it a verbose copy operation for easier monitoring & debugging.
- mv: Moves/renames files or directories. Retains original creation & modification dates.
- mv oldname.txt newname.txt renames the file.
- mv -t [target] [source1] source2 … eg. mv -t /bucket/ directory1 directory2 file1.txt … moves all source arguments into target directory.
- rm: Removes files or directories.
- rm -r folder deletes the folder & its contents.
- sudo rm -rf / will delete everything on the system, so please do refrain from doing that.
- touch: Creates empty files or updates the timestamp of existing files.
- touch newfile.txt creates a new file named newfile.txt.
Viewing & editing files (e.g., cat, nano, vim, less):
Commands for viewing & editing files allow users to read & modify file content.
- cat: Concatenates & displays file content.
- cat file.txt shows the content of file.txt; cat file1 file2 … concatenates all the output into one output stream. No longer used in practice to display files’ contents. (See less.)
- nano: A simple text editor for editing files.
- nano file.txt opens file.txt in the nano editor.
- vim: A powerful text editor for advanced editing.
- vim file.txt opens file.txt in the vim editor.
- vim file.txt +20 opens file.txt at line 20.
- :help (+ <Enter>) for help, :wq to save & quit, and :q! to quit without saving.
- less: Views file content one page at a time; allows for searching in paged output.
- less file.txt allows scrolling through file.txt.
- Press h or ? for help, PgUp/PgDn/Space/Backspace scrolls, / searches; press n for next/N for previous search match. Quit with q.
System administration commands
User & group management (e.g., adduser, usermod, passwd):
Managing users & groups is critical for system administration.
- adduser: Adds new users to the system: adduser newuser creates a new user account.
- addgroup: Adds new groups to the system. addgroup newgroup creates a new group.
- usermod: Modifies existing user accounts: usermod -aG sudo user adds the user to the sudo group.
- passwd: Changes user passwords.
- passwd without parameters changes the password for the current account. Prompts for the current password first.
- sudo passwd newuser sets a password for the newuser account. Be careful when using passwd as root or with sudo. It will not prompt for any current passwords in that case.
File permissions & ownership (e.g., chmod, chown, chgrp):
Controlling file permissions & ownership ensures security and proper access.
- chmod: Changes file permissions.
- chmod 755 script.sh sets the permissions of script.sh.
- chmod +x file1.sh makes file1.sh executable
- chown: Changes file ownership.
- chown user:group file.txt sets user & group ownership of file.txt.
- chown -R user:group Directory1/ recursively sets user & group ownership of folder Directory1.
- chgrp: Changes the group ownership of files. (In practice, chown is more often used for this, that being the more versatile tool.)
- chgrp newgroup file.txt sets the group to newgroup.
Process management (e.g., ps, top, kill, htop):
Process management commands help monitor & control running processes.
- ps: Displays information about active processes.
-
-
- ps aux shows all running processes. (For more detail: ps auxw[ww])
- Useful invocation: ps aux | grep -i [pattern] | awk ‘{print $2}’ | xargs kill -9 will kill any processes matching the (case-insensitive) grep search string pattern.
-
- top: Provides a real-time view of system processes. (Oldschool, small, included in most distros)
- htop: An interactive process viewer; a nicer/newer top. (Press h or ? for help.)
- kill: Terminates processes by PID (process ID as per ps) and sends various other signals to running applications. Signals include:
- SIGHUP (1): Gracefully restarts the application. Used to re-read configuration files without stopping a service. Eg. kill -s HUP <pid>
- SIGINT (2): Interrupts a process from the terminal (Ctrl+C or kill -s INT <pid>). Used to stop a running process.
- SIGQUIT (3): Quits a process & generates a core dump (Ctrl+\ or kill -s QUIT <pid>). Used for debugging.
- SIGKILL (9): Forcefully stops a process. Cannot be caught or ignored. Used when a process is unresponsive. Eg. kill -9 <pid>
- SIGTERM (15): Requests a process to terminate. Default signal for kill command. Allows graceful process cleanup before exiting. Eg. kill 1234 stops the process with PID 1234.
Networking commands
Network configuration & troubleshooting (e.g., ifconfig, ping, netstat):
Networking commands are vital for configuring and troubleshooting network connections.
- ifconfig: Configures network interfaces.
- ifconfig eth0 up brings up the eth0 interface. (Does not work with NetworkManager-managed network interfaces.)
- sudo ifconfig eth0:0 192.168.1.100 netmask 255.255.255.0 creates alias network interface eth0:0 with IP 192.168.1.100 & netmask 255.255.255.0 (in case you eg. need one NIC to respond to more than one subnet)
- ping: Tests connectivity to a host.
- ping 1.1.1.1 pings the host IP address 1.1.1.1 without attempting DNS resolution.
- ping google.com checks the connection to Google. Using a domain name implicitly tests whether DNS resolution is working.
- netstat: Displays network statistics & connections.
- netstat -tulpen displays detailed information as follows:
- -t: Shows TCP connections.
- -u: Shows UDP connections.
- -l: Displays only listening sockets.
- -p: Shows the PID & name of the program to which each socket belongs.
- -e: Displays extended information, such as the user who owns the socket.
- -n: Shows numerical addresses instead of resolving hostnames.
Secure remote operations (e.g., ssh, scp, sftp):
Secure remote commands enable encrypted connections & file transfers.
- ssh: Securely connects to remote servers: ssh user@hostname logs into the remote server.
- scp: Securely copies files between hosts: Best for quick, straightforward file transfers. Syntax & speed advantages.
- scp file.txt user@hostname:/path transfers file.txt to absolute path /path on destination server.
- scp file.txt user@hostname:path/ transfers file.txt to /home/user/path on destination server; relative paths in scp are always relative to remote user’s home directory.
- sftp: Securely transfers files using FTP over SSH: Better for interactive sessions where you need more control over the file operations. sftp user@hostname starts an SFTP session.
Monitoring network traffic (e.g., tcpdump, nmap):
Monitoring commands help analyze network traffic & security.
- tcpdump: Captures network packets: tcpdump -i eth0 captures traffic on eth0.
- nmap: Scans networks for open ports & vulnerabilities: nmap -sP 192.168.1.0/24 scans the local network.
Package management
Installing, updating, & removing software (e.g., apt, yum, dnf):
Package management commands handle software installation & updates.
- apt & dpkg: Manage packages on Debian-based systems. Requires sudo.
- apt install package installs a package.
- dpkg -l lists installed packages.
- aptitude follows apt syntax for CLI operations. Also provides a text-based APT manager if run without parameters, eg. sudo aptitude
- yum , RPM, & dnf: Manages packages on RPM-based systems. Since RHEL8/CentOS8, yum commands have been aliased to dnf for backwards compatibility
- yum update updates all packages.
- dnf remove package removes a package.
- rpm: Manages RPM packages. rpm -qa queries all installed packages.
Advanced operations
Disk usage & management (e.g., df, du, fdisk):
Disk management commands monitor & manage disk space.
- df: Reports filesystem disk space usage: df -h shows disk usage in human-readable format.
- du: Estimates file & directory space usage: du -sh * shows space usage of files & directories recursively, including current working directory & all subdirectories.
- fdisk: Manipulates disk partition tables: fdisk /dev/sda manages partitions on sda.
- cfdisk: A better text-based fdisk GUI: cfdisk /dev/sda manages partitions on sda in a nice ncurses-based user interface.
- lsblk: Lists [all] block devices addressable by the system/on a given device.
- lsblk shows all block devices, typically in tree format.
- lsblk [-f/–fs] /dev/sda5 shows information about a specific filesystem.
Archiving & compression (e.g., tar, gzip, zip):
Archiving & compression commands handle file archives.
- tar & gzip: Archives multiple files into one file: Rarely used separately. Actually, gzip compresses only one file/stream at a time: usually the .tar file (aka “tarball”).
- tar -cvzf archive.tar file1 file2 creates a .tar.gz archive including file1 and file2 using gzip compression.
- To use .bz2 compression: Use -cvjf instead of -cvzf.
- zip & unzip: Creates & unpacks compressed zip archives.
- zip archive.zip file1 file2 creates a zip archive.
- unzip archive.zip unpacks a zip archive.
- atool: Swiss army knife wrapper for all your installed archive backends: Archiving backend is auto-selected based on runtime-supplied archive file extension.
- apack archive.[extension] file1 file2 … to pack selected files into archive.tar.gz … or .zip, .rar, .7z, whatever…
- als archive.zip will list (ls) the contents of archive.zip.
- aunpack archive.7z will unpack the contents of archive.7z to the current working directory. If atool detects that the archive contains many files, it will automagically dump the extracted files into a subdirectory with the name of the archive file.
System monitoring & logging (e.g., dmesg, journalctl, tail, grep):
Monitoring & logging commands help track system activity & logs.
- dmesg: Displays kernel ring buffer messages: dmesg | grep error filters error messages.
- journalctl: Queries & displays systemd logs.
- journalctl -u apache2 shows logs for the Apache service.
- journalctl -xe: Shows detailed systemd journal logs (including error messages) and appends new entries in real-time.
- tail: Views the end of files.
- tail -n 10 file.txt shows the last 10 lines of file.txt.
- tail -f /var/log/syslog continuously displays syslog.
- grep: Searches text using patterns: grep “pattern” file.txt searches for the exact (case-sensitive) string “pattern” in file.txt.
- grep -i edit file.txt does a case-insensitive search in file.txt for edit/EDIT/Edit/etc.
- grep ‘home\|boot’ /etc/fstab searches the /etc/fstab file for lines matching either home OR boot.
Automating tasks using cron:
Cron schedules scripts & commands to run at specific times.
- Create cron jobs using crontab:
- crontab -e edits the cron table.
- crontab -l lists (displays) the current crontab.
- crontab -u [user] -e edits another user’s crontab. Useful for eg. running server applications without root privileges.
- Schedule tasks with time-based syntax: (See man 1 crontab & man 5 crontab for syntax info.)
- 0 5 * * * /path/to/script.sh runs a script daily at 5 AM.
Customizing the shell environment (e.g., .bashrc, .profile):
Customizing the shell environment enhances the user experience.
- Modify .bashrc for Bash customizations: alias ll=’ls -la’ creates an alias.
- Use .profile for environment variables: The line export PATH=$PATH:/new/path adds to the PATH variable.
Thinking terminally: A whole new world to discover
Mastering Linux commands enhances user proficiency and control over the system. These commands enable efficient navigation, management, and customization of the Linux environment, making it a powerful tool for both beginners and experienced users. To continue learning, utilize resources such as online tutorials, forums, and official documentation.
Engage with the Linux community for support, tips, and shared knowledge – the open source philosophy means that there are entire communities out there eager to “pay it forward” for all the great free software and help they’ve gotten over time.
Don’t be afraid to experiment! Practice these commands and explore further. Experimenting with commands and learning new ones will not only deepen your understanding and improve your skills – you’re sure to gain a whole new appreciation for arguably the best user interface ever created.