Mastering Linux Commands: A Functional Guide

Linux commands are the backbone of interaction with the operating system. Understanding them by their function or purpose is the most practical way to learn and leverage the power of the command line. This guide breaks down essential Linux commands into practical categories, providing examples with common arguments to help you navigate, manage, and interact with your system efficiently.
I. File and Directory Management
These commands are fundamental for navigating, creating, modifying, copying, moving, and deleting files and directories within the Linux file system.
ls
- List Directory Contents
- Purpose: Displays a list of files and subdirectories within a specified directory.
- Basic Usage:
ls [options] [directory/file]
- Example with Arguments:
ls -lha /home/user/documents
- Explanation:
-l
(long format): Shows file permissions, number of links, owner name, group name, size, last modification date, and filename.-h
(human-readable): Displays file sizes in human-readable units (e.g., KB, MB, GB).-a
(all): Includes hidden files and directories (those starting with a.
)./home/user/documents
: The specific directory whose contents are to be listed.- Other common arguments:
-R
(recursive): Lists the content of subdirectories as well.-t
: Sorts files by modification time, newest first.-S
: Sorts files by size, largest first.
cd
- Change Directory
- Purpose: Changes the current working directory in the terminal.
- Basic Usage:
cd [directory]
- Example with Arguments:
cd /var/log cd .. cd ~ cd -
- Explanation:
/var/log
: Changes to the absolute path/var/log
...
: Changes to the parent directory of the current directory.~
: Changes to the user's home directory.-
: Changes to the previous working directory.- No arguments: If
cd
is used without arguments, it defaults to changing to the user's home directory.
pwd
- Print Working Directory
- Purpose: Displays the full path of the current working directory.
- Basic Usage:
pwd [options]
- Example with Arguments:
pwd -P
- Explanation:
-P
: Prints the physical directory, without any symbolic links. (e.g., if youcd
into a symlink,pwd -P
shows the actual directory it points to).
mkdir
- Make Directory
- Purpose: Creates new directories (folders).
- Basic Usage:
mkdir [options] directory_name
- Example with Arguments:
mkdir -pv my_project/src/components
- Explanation:
-p
(parents): Creates any necessary parent directories that don't already exist.-v
(verbose): Prints a message for each directory created.
rmdir
- Remove Empty Directory
- Purpose: Deletes empty directories.
- Basic Usage:
rmdir [options] directory_name
- Example with Arguments:
rmdir -p old_project/temp
- Explanation:
-p
(parents): Removes parent directories if they become empty after the specified directory is removed.
rm
- Remove (Delete) Files or Directories
- Purpose: Deletes files or directories. Use with caution!
- Basic Usage:
rm [options] file_or_directory
- Example with Arguments:
rm -rfi old_data/ my_old_file.txt
- Explanation:
-r
(recursive): Required to delete directories and their contents.-f
(force): Deletes without prompting for confirmation (overrides-i
).-i
(interactive): Prompts for confirmation before every removal. (Useful to combine-rf
with-i
to prevent accidental deletion of important files.)- Common (dangerous) combination:
rm -rf directory_name
(Deletes recursively and forcefully, without confirmation). Use with extreme care.
cp
- Copy Files or Directories
- Purpose: Copies files or directories from one location to another.
- Basic Usage:
cp [options] source destination
- Example with Arguments:
cp -av /var/www/html/index.html /tmp/website_backup/ cp -r new_photos/ old_photos_backup/
- Explanation:
-a
(archive): Preserves file attributes (permissions, ownership, timestamps, etc.) and is equivalent to-dR --preserve=all
. Excellent for backups.-v
(verbose): Explains what is being done.-r
(recursive): Required to copy directories and their contents.- Other common arguments:
-i
(interactive): Prompts before overwriting an existing file.-u
(update): Copies only when the source file is newer than the destination or when the destination file is missing.
mv
- Move or Rename Files/Directories
- Purpose: Moves files or directories from one location to another, or renames them.
- Basic Usage:
mv [options] source destination
- Example with Arguments:
mv -i old_report.txt /home/user/reports/ mv -v project_alpha project_beta
- Explanation:
-i
(interactive): Prompts before overwriting an existing file.-v
(verbose): Explains what is being done.- Renaming: When the destination is a new name in the same directory,
mv
acts as a rename command.
touch
- Create Empty Files or Update Timestamps
- Purpose: Creates new empty files. If the file already exists, it updates its access and modification timestamps.
- Basic Usage:
touch [options] filename
- Example with Arguments:
touch -am 202407251030.00 log.txt touch -r reference_file.txt new_file.txt
- Explanation:
-a
: Changes only the access time.-m
: Changes only the modification time.202407251030.00
: Sets the timestamp to July 25, 2024, 10:30:00 (YYMMDDhhmm.ss).-r reference_file.txt
: Uses the access and modification times ofreference_file.txt
fornew_file.txt
.
cat
- Concatenate and Print Files
- Purpose: Displays the content of files, concatenates multiple files, or creates new files via standard input.
- Basic Usage:
cat [options] file(s)
- Example with Arguments:
cat -n /etc/os-release cat file1.txt file2.txt > combined.txt
- Explanation:
-n
: Numbers all output lines./etc/os-release
: Displays the content of this system file.file1.txt file2.txt > combined.txt
: Concatenatesfile1.txt
andfile2.txt
and redirects the combined output tocombined.txt
(overwrites ifcombined.txt
exists).
head
- Display the Beginning of Files
- Purpose: Outputs the first part (default 10 lines) of files.
- Basic Usage:
head [options] file(s)
- Example with Arguments:
head -n 5 /var/log/syslog
- Explanation:
-n 5
: Displays the first 5 lines.
tail
- Display the End of Files
- Purpose: Outputs the last part (default 10 lines) of files.
- Basic Usage:
tail [options] file(s)
- Example with Arguments:
tail -n 20 /var/log/auth.log tail -f /var/log/nginx/access.log
- Explanation:
-n 20
: Displays the last 20 lines.-f
(follow): Outputs appended data as the file grows. This is extremely useful for monitoring log files in real-time.
find
- Search for Files and Directories
- Purpose: Searches for files and directories in a directory hierarchy based on various criteria (name, type, size, time, permissions, owner, etc.).
- Basic Usage:
find [path] [expression]
- Example with Arguments:
find /home/user -name "*.jpg" -type f -size +1M find /var/log -mtime +7 -name "*.log" -delete find . -type d -perm 777 -exec chmod 755 {} \;
- Explanation:
/home/user
: The starting directory for the search.-name "*.jpg"
: Finds files with names ending in.jpg
.-type f
: Specifies to search for regular files (used
for directories,l
for symbolic links).-size +1M
: Finds files larger than 1 Megabyte.-mtime +7
: Finds files modified more than 7 days ago.-delete
: Deletes the found files. Use with extreme caution..
: The current directory.-type d
: Finds directories.-perm 777
: Finds items with permissions set to 777.-exec chmod 755 {} \;
: Executes thechmod 755
command on each found item ({}
represents the found item,\;
marks the end of the command).
grep
- Search for Patterns in Files
- Purpose: Searches for lines containing a specified pattern in files or standard input and prints the matching lines.
- Basic Usage:
grep [options] pattern [file(s)]
- Example with Arguments:
grep -in "error" /var/log/messages grep -r "TODO" ~/projects/my_app/ ps aux | grep "[a]pache"
- Explanation:
-i
(ignore-case): Ignores case distinctions in the pattern.-n
(line-number): Prints the line number of each match."error"
: The pattern to search for./var/log/messages
: The file to search within.-r
(recursive): Recursively searches directories."TODO"
: The pattern to search for.~/projects/my_app/
: The directory to search recursively.ps aux | grep "[a]pache"
: Pipes the output ofps aux
togrep
to filter for processes related to "nginx".
wc
- Word Count (Lines, Words, Characters)
- Purpose: Counts the number of lines, words, and characters (or bytes) in files.
- Basic Usage:
wc [options] file(s)
- Example with Arguments:
wc -l file.txt wc -w document.md another_doc.md ls -l | wc -l
- Explanation:
-l
(lines): Only prints the newline counts.-w
(words): Only prints the word counts.file.txt
: The file to analyze.ls -l | wc -l
: Pipes the output ofls -l
(long listing) towc -l
to count the number of lines, effectively counting the number of items in the directory.
II. System Information & Monitoring
These commands provide details about your system's hardware, kernel, running processes, memory usage, and disk space.
uname
- Print System Information
- Purpose: Displays various system information, including kernel name, network hostname, kernel release, kernel version, and machine hardware name.
- Basic Usage:
uname [options]
- Example with Arguments:
uname -a uname -r
- Explanation:
-a
(all): Prints all available information.-r
: Prints the kernel release.
hostname
- Show System Hostname
- Purpose: Displays or sets the system's hostname.
- Basic Usage:
hostname [options]
- Example with Arguments:
hostname hostname -i
- Explanation:
- No arguments: Shows the current hostname.
-i
: Shows the IP address(es) of the hostname.
uptime
- Show How Long the System Has Been Running
- Purpose: Displays how long the system has been running, current time, number of logged-in users, and load averages.
- Basic Usage:
uptime [options]
- Example with Arguments:
uptime -p
- Explanation:
-p
(pretty): Shows output in a more user-friendly, pretty format.
top
/ htop
- Display and Manage Top Processes Dynamically
- Purpose: Provides a dynamic, real-time view of running processes, CPU usage, memory usage, and other system statistics.
htop
is an enhanced, more user-friendly version oftop
. - Basic Usage:
top
orhtop
- Example with Arguments (
top
):top -u your_username
- Explanation (for
top
):-u your_username
: Displays only processes owned byyour_username
.- Inside
top
/htop
:q
: Quit.k
: Kill a process (requires PID).P
(intop
): Sorts by CPU usage.M
(intop
): Sorts by memory usage.
ps
- Show Running Processes
- Purpose: Reports a snapshot of the current processes. Unlike
top
, it's not real-time. - Basic Usage:
ps [options]
- Example with Arguments:
ps aux ps -ef | grep "nginx"
- Explanation:
aux
(BSD style):a
: Show processes for all users.u
: Display user-oriented format.x
: Show processes not attached to a terminal.
-ef
(System V style):e
: Select all processes.f
: Do a full-format listing.
| grep "nginx"
: Pipes the output togrep
to filter for processes related to "nginx".
free
- Display Free and Used Memory
- Purpose: Shows the total, used, and free amounts of physical and swap memory in the system.
- Basic Usage:
free [options]
- Example with Arguments:
free -h free -g
- Explanation:
-h
(human-readable): Displays output in easily readable units (e.g., MB, GB).-g
(giga): Displays output in gigabytes.
df
- Show Disk Space Usage
- Purpose: Reports file system disk space usage.
- Basic Usage:
df [options] [file_system]
- Example with Arguments:
df -hT /dev/sda1
- Explanation:
-h
(human-readable): Displays sizes in human-readable format.-T
(type): Prints the file system type./dev/sda1
: Specific file system to report on.
du
- Show Directory/File Size
- Purpose: Estimates file space usage by files or directories.
- Basic Usage:
du [options] [file_or_directory]
- Example with Arguments:
du -sh /var/cache du -h --max-depth=1 /home/user
- Explanation:
-s
(summarize): Displays only a total for each argument.-h
(human-readable): Displays sizes in human-readable format./var/cache
: The directory to analyze.--max-depth=1
: Displays disk usage only for the first level of subdirectories.
dmesg
- Display Messages from the Kernel Ring Buffer
- Purpose: Prints the kernel messages from the boot process and ongoing kernel activities, useful for hardware troubleshooting.
- Basic Usage:
dmesg [options]
- Example with Arguments:
dmesg | grep -i "usb" dmesg -T
- Explanation:
| grep -i "usb"
: Pipes the output togrep
to filter for lines containing "usb" (case-insensitive).-T
(human-readable time): Prints timestamps in a human-readable format.
lsof
- List Open Files
- Purpose: Lists information about files opened by processes. Can be used to find out which process is using a particular file or network connection.
- Basic Usage:
lsof [options]
- Example with Arguments:
sudo lsof -i :80 sudo lsof /var/log/syslog
- Explanation:
-i :80
: Lists processes using network connections on port 80./var/log/syslog
: Lists processes that have this specific file open.sudo
: Often required aslsof
needs root privileges to view all open files across the system.
systemctl
- Manage Systemd Services
- Purpose: Controls the systemd system and service manager. Used to start, stop, enable, disable, and check the status of services.
- Basic Usage:
systemctl [command] [service]
- Example with Arguments:
sudo systemctl status apache2 sudo systemctl start sshd sudo systemctl enable nginx systemctl --failed
- Explanation:
status apache2
: Shows the current status of theapache2
service.start sshd
: Starts thesshd
(SSH daemon) service.enable nginx
: Configuresnginx
to start automatically at boot.--failed
: Lists all systemd units that are in a failed state.
journalctl
- View System Logs
- Purpose: Queries and displays messages from the systemd journal, providing a centralized log management solution.
- Basic Usage:
journalctl [options]
- Example with Arguments:
journalctl -u sshd --since "1 hour ago" journalctl -f journalctl -b 0
- Explanation:
-u sshd
: Displays logs specifically for thesshd
service.--since "1 hour ago"
: Filters logs from the last hour.-f
(follow): Continuously displays new log entries as they arrive (liketail -f
).-b 0
: Displays logs from the current boot. (-b -1
for previous boot, etc.)
III. User and Permission Management
These commands are essential for managing user accounts, groups, and controlling access rights to files and directories.
useradd
/ adduser
- Add a New User
- Purpose: Creates a new user account.
adduser
is often a more user-friendly script that usesuseradd
in the background. - Basic Usage:
sudo useradd [options] username
orsudo adduser username
- Example with Arguments:
sudo useradd -m -s /bin/bash -G sudo,www-data newdev sudo adduser staging_user
- Explanation:
-m
: Creates the user's home directory if it doesn't exist.-s /bin/bash
: Sets/bin/bash
as the user's default login shell.-G sudo,www-data
: Adds the user to thesudo
andwww-data
supplementary groups.newdev
: The username for the new account.adduser staging_user
: Theadduser
command is interactive and prompts for details like password, full name, etc.
userdel
/ deluser
- Delete a User
- Purpose: Deletes a user account.
deluser
is often the more user-friendly wrapper. - Basic Usage:
sudo userdel [options] username
orsudo deluser username
- Example with Arguments:
sudo userdel -r olduser sudo deluser test_user
- Explanation:
-r
(remove-home): Removes the user's home directory and mail spool along with the account.olduser
: The username to delete.deluser test_user
: Deletes the user without removing their home directory by default.
passwd
- Change User Password
- Purpose: Sets or changes a user's password.
- Basic Usage:
passwd [options] [username]
- Example with Arguments:
passwd # Change current user's password sudo passwd newdev # Change password for 'newdev' sudo passwd -l john # Lock user 'john's password (disable login) sudo passwd -u john # Unlock user 'john's password
- Explanation:
- No arguments: Changes the password for the current logged-in user.
newdev
: Specifies the user whose password is to be changed (requiressudo
for other users).-l
(lock): Locks the specified user's password, preventing them from logging in.-u
(unlock): Unlocks the specified user's password.
usermod
- Modify User Account
- Purpose: Modifies an existing user account's properties.
- Basic Usage:
sudo usermod [options] username
- Example with Arguments:
sudo usermod -aG docker,admin myuser sudo usermod -s /bin/zsh newuser sudo usermod -l newname oldname
- Explanation:
-aG docker,admin
: Appends the user to thedocker
andadmin
groups. (-a
for append,-G
for supplementary groups).-s /bin/zsh
: Changes the user's default login shell tozsh
.-l newname oldname
: Renamesoldname
user tonewname
.
cat /etc/passwd
- View All Users from /etc/passwd
- Purpose: Lists all user entries, including system accounts, by displaying the content of the
/etc/passwd
file. - Basic Usage:
cat /etc/passwd
- Example with Arguments:
- Directly viewing the file:
Example output:cat /etc/passwd
root:x:0:0:root:/root:/bin/bash john:x:1001:1001::/home/john:/bin/bash guest:x:1002:1002::/home/guest:/bin/bash
- Directly viewing the file:
cut -d: -f1 /etc/passwd
- Get Only Usernames Using cut
- Purpose: Extracts and displays only the usernames from the
/etc/passwd
file. - Basic Usage:
cut -d: -f1 /etc/passwd
- Example with Arguments:
- Using
cut
to isolate usernames:
Example output:cut -d: -f1 /etc/passwd
root john guest
- Using
awk -F: '{ print $1 }' /etc/passwd
- Use awk
to List Usernames
- Purpose: Displays only the usernames from the
/etc/passwd
file using theawk
command. - Basic Usage:
awk -F: '{ print $1 }' /etc/passwd
- Example with Arguments:
- Using
awk
to print the first field:
Example output:awk -F: '{ print $1 }' /etc/passwd
root john guest
- Using
getent passwd
- Use getent
to Fetch User Info
- Purpose: Retrieves user entries from configured databases (e.g., local files, LDAP), providing a more comprehensive view than just
/etc/passwd
. - Basic Usage:
getent passwd
- Example with Arguments:
- Fetching all user information:
Example output:getent passwd
root:x:0:0:root:/root:/bin/bash john:x:1001:1001::/home/john:/bin/bash guest:x:1002:1002::/home/guest:/bin/bash
- Get Usernames Only via
getent
: Pipe the output tocut
to get just the usernames:
Example output:getent passwd | cut -d: -f1
root john guest
- Fetching all user information:
who
/ users
- See Currently Logged-In Users
- Purpose: Displays information about users who are currently logged into the system.
- Basic Usage:
who
orusers
- Example with Arguments:
- Using
who
for detailed login info:
Example output:who
john tty7 2025-08-04 08:12 (:0) guest pts/0 2025-08-04 09:30 (192.168.1.50)
- Using
users
for a concise list of usernames:
Example output:users
john guest
- Using
getent passwd [username]
- Check If a Specific User Exists
- Purpose: Verifies the existence of a specific user account by querying system databases.
- Basic Usage:
getent passwd [username]
- Example with Arguments:
- Checking if user
john
exists:
Example output:getent passwd john
john:x:1001:1001::/home/john:/bin/bash
- Checking for a non-existent user (no output if not found):
Example output:getent passwd non_existent_user
# (no output)
- Checking if user
groups
- Show Group Memberships
- Purpose: Displays the groups a user belongs to.
- Basic Usage:
groups [username]
- Example with Arguments:
groups groups your_username
- Explanation:
- No arguments: Shows the groups for the current user.
your_username
: Shows the groups for the specified user.
id
- Display User Identity Information
- Purpose: Displays user and group IDs, and groups for the current or a specified user.
- Basic Usage:
id [options] [username]
- Example with Arguments:
id id -gn your_username
- Explanation:
- No arguments: Shows UIDs, GIDs, and groups for the current user.
-g
(group): Prints only the effective group ID.-n
(name): Prints the name instead of the number.
chmod
- Change File Permissions
- Purpose: Changes the file mode bits (permissions) of a file or directory.
- Basic Usage:
chmod [options] mode file_or_directory
- Example with Arguments:
chmod 755 script.sh chmod u+x,go=r myfile.txt chmod -R 644 my_data_folder/
- Explanation:
755
(octal notation): Sets permissions torwx
for owner,rx
for group,rx
for others.r=4
,w=2
,x=1
7 = 4+2+1
(read, write, execute)5 = 4+1
(read, execute)
u+x
: Adds execute permission for the user (owner).go=r
: Sets read permission for group and others, removing other permissions they might have had.-R
(recursive): Changes permissions recursively for contents of the directory.644
: Sets permissions torw-
for owner,r--
for group,r--
for others.
chown
- Change File Owner and Group
- Purpose: Changes the user owner and/or group owner of files or directories.
- Basic Usage:
chown [options] new_owner[:new_group] file_or_directory
- Example with Arguments:
sudo chown www-data:www-data /var/www/html sudo chown -R root:developers /srv/app_data
- Explanation:
www-data:www-data
: Sets both the owner and group towww-data
./var/www/html
: The target file or directory.-R
(recursive): Changes ownership recursively for contents of the directory.root:developers
: Sets owner toroot
and group todevelopers
.
sudo
- Execute Commands as Root
- Purpose: Allows a permitted user to execute a command as the superuser (root) or another user, as specified by the
sudoers
file. - Basic Usage:
sudo command [arguments]
- Example with Arguments:
sudo apt update sudo -u anotheruser nano /home/anotheruser/file.txt
- Explanation:
apt update
: Executes theapt update
command with root privileges.-u anotheruser
: Executes thenano
command asanotheruser
instead ofroot
.
IV. Networking
These commands are used for network configuration, testing connectivity, data transfer, and troubleshooting.
ping
- Test Network Connectivity
- Purpose: Sends ICMP ECHO_REQUEST packets to network hosts to test reachability and measure round-trip time.
- Basic Usage:
ping [options] destination
- Example with Arguments:
ping -c 4 google.com ping -i 2 192.168.1.1
- Explanation:
-c 4
: Sends only 4 echo requests and then stops.google.com
: The hostname to ping.-i 2
: Sets the interval between packets to 2 seconds.192.168.1.1
: An IP address to ping (e.g., your router).
ip
- Show / Manipulate Routing, Devices, Policy Routing and Tunnels
- Purpose: The modern and recommended utility for network interface configuration. Replaces older commands like
ifconfig
. - Basic Usage:
ip [options] object command
- Example with Arguments:
ip addr show ip link show eth0 ip route show sudo ip addr add 192.168.1.100/24 dev eth0
- Explanation:
addr show
: Displays network interface addresses and their configurations.link show eth0
: Shows link layer information for theeth0
interface.route show
: Displays the IP routing table.sudo ip addr add 192.168.1.100/24 dev eth0
: Adds an IP address to theeth0
interface. (Requiressudo
)
netstat
/ ss
- Show Network Connections
- Purpose:
netstat
(Network Statistics) andss
(Socket Statistics) display network connections, routing tables, interface statistics, etc.ss
is newer and generally faster/more capable thannetstat
. - Basic Usage:
netstat [options]
orss [options]
- Example with Arguments:
netstat -tulnp # (legacy, still common) ss -tulnp ss -s
- Explanation:
-t
: TCP connections.-u
: UDP connections.-l
: Listening sockets.-n
: Numeric output (don't resolve hostnames/ports).-p
: Show the PID/program name owning the socket.ss -s
: Displays summary statistics for sockets.
wget
- Download Files from the Web
- Purpose: Non-interactive network downloader. Retrieves files from the web using HTTP, HTTPS, and FTP protocols.
- Basic Usage:
wget [options] URL
- Example with Arguments:
wget -c [https://example.com/large_file.zip](https://example.com/large_file.zip) wget -r -l1 -np [https://example.com/downloads/](https://example.com/downloads/)
- Explanation:
-c
(continue): Resumes getting a partially downloaded file.-r
(recursive): Recursively downloads files from the URL.-l1
(level 1): Limits recursion to one level deep.-np
(no-parent): Prevents going up to the parent directory when retrieving recursively.
curl
- Transfer Data with URL Syntax
- Purpose: A versatile command-line tool for transferring data with URL syntax, supporting a wide range of protocols (HTTP, HTTPS, FTP, FTPS, SCP, SFTP, SMB, etc.).
- Basic Usage:
curl [options] URL
- Example with Arguments:
curl -O [https://example.com/api/data.json](https://example.com/api/data.json) curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' [https://api.example.com/resource](https://api.example.com/resource) curl -I [https://google.com](https://google.com)
- Explanation:
-O
(remote-name): Writes output to a local file named like the remote file.-X POST
: Specifies the HTTP request method as POST.-H "Content-Type: application/json"
: Adds an HTTP header.-d '{"key":"value"}'
: Sends data in a POST request body.-I
(head): Fetches only the HTTP headers.
ssh
- Securely Connect to Remote Hosts
- Purpose: The Secure Shell (SSH) client program for remote login to a server, secure file transfers, and secure command execution.
- Basic Usage:
ssh [options] user@host
- Example with Arguments:
ssh username@your_server_ip ssh -p 2222 devuser@staging.example.com ssh -i ~/.ssh/id_rsa_private_key production_admin@prod.example.com "sudo systemctl restart apache2"
- Explanation:
username@your_server_ip
: Specifies the username and the remote server's IP address or hostname.-p 2222
: Specifies a custom port for the SSH connection (default is 22).-i ~/.ssh/id_rsa_private_key
: Specifies the path to a private key file for authentication."sudo systemctl restart apache2"
: Executes the given command on the remote server and then closes the connection.
traceroute
- Trace the Path Packets Take to a Host
- Purpose: Displays the route (hops) that packets take to reach a network host. Useful for network troubleshooting.
- Basic Usage:
traceroute [options] hostname_or_ip
- Example with Arguments:
traceroute google.com traceroute -n -m 30 8.8.8.8
- Explanation:
-n
: Do not resolve IP addresses to hostnames (speeds up output).-m 30
: Sets the maximum number of hops (TTL) to 30.
nslookup
/ dig
- Query DNS Information
- Purpose:
nslookup
is a network administration command-line tool for querying the Domain Name System (DNS) to obtain domain name or IP address mapping.dig
is a more modern and powerful alternative. - Basic Usage:
nslookup [options] domain
ordig [options] domain
- Example with Arguments:
nslookup example.com dig example.com A dig @8.8.8.8 example.com MX
- Explanation:
example.com
: The domain to query.A
: Queries for A records (IPv4 addresses).@8.8.8.8
: Specifies using Google's DNS server (8.8.8.8).MX
: Queries for MX records (mail exchange servers).
V. Archiving and Compression
These commands are used to create compressed archives of files and directories, and to extract them.
tar
- Archive Files
- Purpose: Creates and extracts archive files (often used with compression like gzip/bzip2). It bundles multiple files into a single
.tar
archive. - Basic Usage:
tar [options] archive_name file(s)_or_directory(s)
- Example with Arguments:
tar -cvf my_archive.tar my_folder/file1.txt tar -czvf my_backup.tar.gz /var/www/html tar -xzvf my_backup.tar.gz -C /tmp/restored_data
- Explanation:
-c
(create): Creates a new archive.-v
(verbose): Displays file names as they are added or extracted.-f file.tar
: Specifies the name of the archive file.-z
(gzip): Compresses/decompresses the archive using gzip. (Creates.tar.gz
or.tgz
)-x
(extract): Extracts files from an archive.-C /tmp/restored_data
: Changes to the specified directory before extracting.- Other common arguments:
-j
(bzip2): Compresses/decompresses with bzip2 (for.tar.bz2
or.tbz
).-J
(xz): Compresses/decompress with xz (for.tar.xz
or.txz
).
gzip
/ gunzip
- Compress/Decompress Files
- Purpose: Compresses files into
.gz
format (gzip
) and decompresses them (gunzip
). - Basic Usage:
gzip [options] file
orgunzip [options] file.gz
- Example with Arguments:
gzip myfile.txt gunzip -k compressed_log.gz gzip -r my_data_folder/
- Explanation:
gzip myfile.txt
: Compressesmyfile.txt
intomyfile.txt.gz
, deleting the originalmyfile.txt
.gunzip -k compressed_log.gz
: Decompressescompressed_log.gz
tocompressed_log
, keeping the original compressed file.-r
(recursive): Recursively compresses files in directories.
zip
/ unzip
- Compress/Decompress Files (Common Across OSes)
- Purpose: Archives and compresses files into
.zip
format, widely compatible across different operating systems. - Basic Usage:
zip [options] archive.zip file(s)_or_directory(s)
orunzip [options] archive.zip
- Example with Arguments:
zip -r website_files.zip /var/www/html unzip -l my_archive.zip unzip -d /tmp/extract_here documents.zip
- Explanation:
-r
(recursive): Includes subdirectories when zipping.website_files.zip
: The name of the zip archive to create.-l
(list): Lists the contents of the zip archive without extracting.-d /tmp/extract_here
: Extracts files to the specified directory.
bzip2
/ bunzip2
- Compress/Decompress Files (High Compression)
- Purpose: Compresses/decompresses files using the bzip2 algorithm, known for better compression ratios than gzip, but typically slower.
- Basic Usage:
bzip2 [options] file
orbunzip2 [options] file.bz2
- Example with Arguments:
bzip2 large_data.csv bunzip2 -f archive.bz2
- Explanation:
bzip2 large_data.csv
: Compresseslarge_data.csv
tolarge_data.csv.bz2
, deleting the original.-f
(force): Forcefully decompresses, even if the output file already exists.
VI. Text Processing
These commands are powerful for manipulating, filtering, transforming, and analyzing text data, often used in combination with pipes (|
).
sort
- Sort Lines of Text Files
- Purpose: Sorts lines of text files.
- Basic Usage:
sort [options] file(s)
- Example with Arguments:
sort -r names.txt cat data.csv | sort -t',' -k2
- Explanation:
-r
(reverse): Sorts in reverse (descending) order.-t','
: Uses comma as the field separator.-k2
: Sorts based on the second field.
uniq
- Report or Omit Repeated Lines
- Purpose: Filters adjacent duplicate lines from a sorted file.
- Basic Usage:
uniq [options] [input_file] [output_file]
- Example with Arguments:
sort words.txt | uniq -c cat numbers.txt | uniq -d
- Explanation:
sort words.txt | uniq -c
: Sorts thewords.txt
file, then counts and prefixes each unique line with the number of occurrences.-d
(repeated): Only prints duplicate lines.
cut
- Remove Sections from Each Line of Files
- Purpose: Extracts sections from each line of files or standard input, based on bytes, characters, or fields.
- Basic Usage:
cut [options] file(s)
- Example with Arguments:
cat /etc/passwd | cut -d':' -f1,7 echo "Linux is awesome" | cut -c 1-5
- Explanation:
-d':'
: Uses colon as the field delimiter.-f1,7
: Extracts the first and seventh fields.-c 1-5
: Extracts characters from position 1 to 5.
paste
- Merge Lines of Files
- Purpose: Merges lines of files, typically combining corresponding lines from multiple input files into single lines of output.
- Basic Usage:
paste [options] file(s)
- Example with Arguments:
paste names.txt emails.txt paste -d',' file1.txt file2.txt file3.txt
- Explanation:
names.txt emails.txt
: Pastes the lines ofnames.txt
andemails.txt
side-by-side, separated by a tab (default delimiter).-d','
: Uses a comma as the delimiter between columns.
sed
- Stream Editor for Filtering and Transforming Text
- Purpose: A powerful non-interactive stream editor for filtering and transforming text. It reads text line by line, applies specified operations, and outputs the result.
- Basic Usage:
sed [options] 'script' file(s)
- Example with Arguments:
sed 's/old_text/new_text/g' document.txt sed -i '/^#/d' config.ini cat data.txt | sed 's/foo/bar/2'
- Explanation:
's/old_text/new_text/g'
: Substitutes all occurrences (g
for global) ofold_text
withnew_text
.-i
(in-place): Edits the file directly instead of printing to standard output.'/^#/d'
: Deletes lines that start with#
(comments).cat data.txt | sed 's/foo/bar/2'
: Pipes content ofdata.txt
tosed
, which replaces the second occurrence offoo
withbar
on each line.
awk
- Pattern Scanning and Processing Language
- Purpose: A very powerful text processing language designed for pattern scanning and processing. Ideal for complex text transformations and report generation.
- Basic Usage:
awk [options] 'program' file(s)
- Example with Arguments:
awk '{print $1, $3}' access.log cat /etc/passwd | awk -F: '{print "User:", $1, "\tShell:", $7}' df -h | awk 'NR > 1 {print $1, $5}'
- Explanation:
'{print $1, $3}'
: Prints the first and third fields (space is default delimiter).-F:
: Sets the field separator to a colon.'{print "User:", $1, "\tShell:", $7}'
: Prints "User:", the first field, a tab, "Shell:", and the seventh field.NR > 1
: Processes records (lines) starting from the second line (skips header).{print $1, $5}
: Prints the first and fifth fields ofdf -h
output.
VII. Interactive Text Editors
Interactive text editors are indispensable tools on the Linux command line for creating, viewing, and modifying configuration files, scripts, code, and plain text documents. Unlike stream editors like sed
or awk
, these tools provide a full-screen interface for direct manipulation of file content.
Vim
/ Neovim
- Powerful Modal Text Editor
- Purpose:
Vim
(Vi IMproved) is a highly configurable and efficient text editor designed for programmers and power users.Neovim
is a modern fork of Vim, aiming for improved extensibility and usability. Both are famous for their modal editing paradigm. - Basic Usage:
vim [filename]
ornvim [filename]
Key Concepts: Modal Editing Vim operates in different modes, each with a specific purpose. This design allows for incredibly fast and efficient text manipulation once mastered, as most keystrokes are commands rather than text insertions.
- Normal Mode (Command Mode): This is the default mode when you open Vim. In this mode, keystrokes are interpreted as commands (e.g., for navigation, deletion, copying, pasting). You do not type text directly here.
- How to enter: Press
Esc
(repeatedly, if unsure).
- How to enter: Press
- Insert Mode: Used for inserting and typing text into the file.
- How to enter:
i
: Insert at the current cursor position.a
: Append after the current cursor position.o
: Open a new line below the current line and enter insert mode.I
: Insert at the beginning of the current line.A
: Append at the end of the current line.O
: Open a new line above the current line and enter insert mode.
- How to enter:
- Visual Mode: Used for selecting blocks of text to apply commands to (e.g., copy, delete, change permissions).
- How to enter:
v
: Character-wise visual mode.V
: Line-wise visual mode.Ctrl-v
: Block-wise visual mode.
- How to enter:
- Command-Line Mode (Ex Mode): Used for executing powerful commands, often starting with
:
(colon), to perform actions like saving, quitting, search/replace, or running external commands.- How to enter: Press
:
from Normal Mode.
- How to enter: Press
- Normal Mode (Command Mode): This is the default mode when you open Vim. In this mode, keystrokes are interpreted as commands (e.g., for navigation, deletion, copying, pasting). You do not type text directly here.
Common Commands (from Normal Mode):
- Navigation:
h
,j
,k
,l
: Move cursor left, down, up, right.w
,b
: Move forward/backward a word.0
,^
: Move to beginning of line (first character).$
: Move to end of line.gg
: Go to the first line of the file.G
: Go to the last line of the file.:<line_number>
thenEnter
: Go to a specific line number.
- Editing/Manipulation:
x
: Delete character under cursor.dw
: Delete word.dd
: Delete (cut) current line.yy
: Yank (copy) current line.p
: Paste content after the cursor/line.P
: Paste content before the cursor/line.u
: Undo last change.Ctrl-r
: Redo last undone change.r<char>
: Replace character under cursor with<char>
.cw
: Change word (deletes word, enters insert mode).cc
: Change line (deletes line, enters insert mode).
- Search and Replace (from Command-Line Mode):
:/pattern
: Search forward forpattern
.s/old/new/g
: Substituteold
withnew
globally on the current line.:%s/old/new/g
: Substituteold
withnew
globally throughout the entire file.:%s/old/new/gc
: Substitute with confirmation for each instance.
- Saving and Quitting (from Command-Line Mode):
:w
: Save the file.:q
: Quit Vim.:wq
or:x
: Save and quit.:q!
: Quit without saving (discard changes).:w! filename
: Save to a new filename (force overwrite if it exists).
- Navigation:
Example Usage:
vim my_script.sh # Open my_script.sh in Vim # (Inside Vim, in Normal Mode) i # Enter Insert Mode to start typing # ... type your script content ... Esc # Exit Insert Mode, return to Normal Mode :wq # Save and quit
Nano
- Simple and User-Friendly Text Editor
- Purpose:
Nano
is an easy-to-use, beginner-friendly text editor. It displays common keyboard shortcuts directly at the bottom of the screen, making it intuitive for new users. - Basic Usage:
nano [options] [filename]
- Key Concepts: Direct Editing
Nano operates primarily in a single mode, where you can type text directly, similar to a simple notepad application. Commands are executed using modifier keys (typically
Ctrl
orAlt
). Common Commands (Displayed at the bottom of the screen):
Ctrl+G
(Get Help): Opens the help menu with all commands.Ctrl+X
(Exit): Exits Nano. Prompts to save if there are unsaved changes.Ctrl+O
(Write Out): Saves the current file.Ctrl+W
(Where Is): Searches for text.Ctrl+Y
(Prev Page): Scrolls up one page.Ctrl+V
(Next Page): Scrolls down one page.Ctrl+K
(Cut Text): Cuts the current line.Ctrl+U
(Uncut Text): Pastes the cut text.Ctrl+C
(Cur Pos): Displays the current cursor position.Ctrl+D
(Delete): Deletes the character under the cursor.Alt+R
(Replace): Finds and replaces text.Alt+A
(Mark): Start/stop marking text for selection (like visual mode).Alt+6
(Copy Text): Copies marked text.
Example Usage:
nano my_notes.txt # Open or create my_notes.txt in Nano # (Inside Nano) # Type your notes directly Ctrl+O # Press Ctrl+O to save Enter # Confirm filename Ctrl+X # Press Ctrl+X to exit
Emacs
- Extensible, Customizable, Self-Documenting Text Editor
- Purpose:
Emacs
is more than just a text editor; it's a powerful and highly extensible environment, often considered an operating system within an operating system. It's famous for its deep customization capabilities via Emacs Lisp. - Basic Usage:
emacs [filename]
- Key Concepts: Buffer-Centric, Highly Customizable
Emacs operates on "buffers" which represent files or other data. It has a single primary editing mode but uses a complex system of key combinations (chords), often involving
Ctrl
(C-
) andAlt
(M-
or Meta key, which is usuallyAlt
on modern keyboards). Common Commands (Often called "Key Chords"):
- General:
C-x C-c
: Exit Emacs (saves modified buffers).C-x C-f
: Find file (open).C-x C-s
: Save file.C-x s
: Save all buffers.C-g
: Cancel the current command.C-h t
: Emacs Tutorial (highly recommended for beginners).
- Navigation:
C-f
: Forward character.C-b
: Backward character.C-n
: Next line.C-p
: Previous line.M-f
: Forward word.M-b
: Backward word.C-a
: Beginning of line.C-e
: End of line.M-<
: Beginning of buffer (file).M->
: End of buffer (file).
- Editing/Manipulation:
C-d
: Delete character.M-d
: Delete word.C-k
: Kill (cut) line from cursor to end.C-y
: Yank (paste).C-SPACE
: Set mark (start selection).C-w
: Kill region (cut selected text).C-/
orC-_
: Undo.C-s
: Incremental search forward.C-r
: Incremental search backward.M-%
: Query Replace (find and replace with confirmation).
- Example (Query Replace):
M-%
(Then typestring_to_find
,Enter
)- (Then type
string_to_replace
,Enter
) - (Then type
y
for yes,n
for no,!
for replace all,.
for replace and exit,q
for quit)
- General:
Example Usage:
emacs my_config.conf # Open my_config.conf in Emacs # (Inside Emacs) # ... type your configuration ... C-x C-s # Press Ctrl+X then Ctrl+S to save C-x C-c # Press Ctrl+X then Ctrl+C to exit
Micro
- Modern and Intuitive Text Editor
- Purpose:
Micro
is a modern, terminal-based text editor that aims to be a successor tonano
by being easy to use while offering modern features like mouse support, syntax highlighting, plugins, and multiple cursors, without the steep learning curve of Vim or Emacs. - Basic Usage:
micro [options] [filename]
- Key Concepts: Keyboard and Mouse Support, Modern Features
Micro behaves much like graphical text editors. You can type directly, use standard
Ctrl
orCmd
key combinations (likeCtrl+S
for save,Ctrl+C
for copy), and even use the mouse for selection and cursor placement. Common Commands:
Ctrl+S
: Save file.Ctrl+Q
: Quit.Ctrl+C
: Copy selected text.Ctrl+V
: Paste text.Ctrl+X
: Cut selected text.Ctrl+Z
: Undo.Ctrl+Y
: Redo.Ctrl+F
: Find.Ctrl+R
: Replace.Ctrl+N
: New buffer (new file).Ctrl+O
: Open file.Ctrl+E
: Execute command (opens a command prompt at the bottom).- Mouse Support: Click to move cursor, drag to select text.
- Configuring: Micro uses a
settings.json
file (usually in~/.config/micro/
), which you can edit usingmicro ~/.config/micro/settings.json
.
Example Usage:
micro new_feature.js # Open new_feature.js in Micro # (Inside Micro) # Type your code Ctrl+S # Save Ctrl+Q # Quit
VIII. Package Management
These commands are distribution-specific and are used for installing, updating, and removing software packages on your system.
apt
/ apt-get
/ apt-cache
(Debian/Ubuntu)
- Purpose: The primary command-line tool for managing packages on Debian-based systems (Ubuntu, Mint, etc.).
apt
is a newer, more user-friendly interface. - Basic Usage:
sudo apt [command] [package]
- Example with Arguments:
sudo apt update sudo apt upgrade -y sudo apt install neofetch sudo apt remove neofetch apt search firefox apt show nginx
- Explanation:
update
: Updates the list of available packages from repositories.upgrade -y
: Upgrades all installed packages to their newest versions.-y
automatically answers 'yes' to prompts.install neofetch
: Installs theneofetch
package.remove neofetch
: Removes theneofetch
package.search firefox
: Searches for packages related to "firefox".show nginx
: Displays detailed information about thenginx
package.
yum
/ dnf
(Red Hat/Fedora/CentOS)
- Purpose:
dnf
is the next-generation package manager for RPM-based distributions, replacingyum
in newer versions of Fedora, CentOS Stream, and RHEL. - Basic Usage:
sudo dnf [command] [package]
- Example with Arguments:
sudo dnf check-update sudo dnf upgrade -y sudo dnf install httpd sudo dnf remove httpd dnf search nodejs
- Explanation:
check-update
: Checks for available updates.upgrade -y
: Upgrades all installed packages.install httpd
: Installs thehttpd
(Apache HTTP Server) package.remove httpd
: Removes thehttpd
package.search nodejs
: Searches for packages related to "nodejs".
pacman
(Arch Linux)
- Purpose: The default package manager for Arch Linux and its derivatives (e.g., Manjaro). Known for its speed and simplicity.
- Basic Usage:
sudo pacman [options] [package]
- Example with Arguments:
sudo pacman -Syu sudo pacman -S firefox sudo pacman -R firefox pacman -Qs kernel
- Explanation:
-Syu
: Synchronizes package databases (-S
), updates all packages (-y
), and refreshes local package lists (-u
).-S firefox
: Installs thefirefox
package.-R firefox
: Removes thefirefox
package.-Qs kernel
: Queries (-Q
) for packages installed on the system (s
) that contain "kernel".
zypper
(openSUSE)
- Purpose: The command-line package manager for openSUSE and SUSE Linux Enterprise (SLE).
- Basic Usage:
sudo zypper [command] [package]
- Example with Arguments:
sudo zypper refresh sudo zypper update sudo zypper install vim sudo zypper remove vim zypper search php
- Explanation:
refresh
: Refreshes all repositories.update
: Updates all installed packages.install vim
: Installs thevim
package.remove vim
: Removes thevim
package.search php
: Searches for packages related to "php".
IX. Shell Utilities
These commands are used for interacting with the shell itself, managing command history, creating shortcuts, and accessing documentation.
history
- Show Command History
- Purpose: Displays a list of previously executed commands.
- Basic Usage:
history [options]
- Example with Arguments:
history history 10 !500 # Re-execute command number 500 !grep # Re-execute the last command that started with 'grep'
- Explanation:
- No arguments: Shows the entire command history.
10
: Shows the last 10 commands.!500
: Executes the command corresponding to history number 500.!grep
: Executes the most recent command that started withgrep
.
alias
- Create Temporary Command Shortcuts
- Purpose: Creates temporary shortcuts or alternative names for commands or sequences of commands.
- Basic Usage:
alias [name='command']
- Example with Arguments:
alias ll='ls -lha' alias myip='ip addr show | grep "inet " | grep -v 127.0.0.1 | awk "{print $2}" | cut -d/ -f1' alias # To list all current aliases unalias ll # To remove an alias
- Explanation:
ll='ls -lha'
: Creates an aliasll
that executesls -lha
.myip='...'
: Creates a complex alias to get your main IP address.- No arguments: Lists all currently defined aliases.
unalias ll
: Removes thell
alias.- Note: Aliases created this way are temporary and will disappear when the terminal session closes. To make them permanent, add them to your shell's configuration file (e.g.,
~/.bashrc
for Bash,~/.zshrc
for Zsh).
echo
- Display a Line of Text
- Purpose: Prints text or variables to the standard output.
- Basic Usage:
echo [options] [string]
- Example with Arguments:
echo "Hello, Linux World!" echo $PATH echo -e "Line 1\nLine 2\twith tab"
- Explanation:
"Hello, Linux World!"
: Prints the literal string.$PATH
: Prints the value of thePATH
environment variable.-e
: Enables interpretation of backslash escapes (like\n
for newline,\t
for tab).
man
- Display the Manual Page for a Command
- Purpose: Displays the online reference manual pages (man pages) for commands, utilities, and functions. This is your go-to resource for detailed information on any command.
- Basic Usage:
man [section] command_name
- Example with Arguments:
man ls man 5 passwd # To view the file format for passwd
- Explanation:
ls
: Displays the manual page for thels
command.5 passwd
: Displays the manual page forpasswd
from section 5 (file formats), aspasswd
also has a command in section 1.
whatis
- Display One-line Manual Page Descriptions
- Purpose: Displays a one-line description from the manual page for a given command. Quicker than
man
for a brief overview. - Basic Usage:
whatis command_name
- Example with Arguments:
whatis ls whatis grep
- Explanation:
ls
: Shows a short description of thels
command.
which
- Locate a Command
- Purpose: Shows the full path of the executable that would be run when you type a command.
- Basic Usage:
which command_name
- Example with Arguments:
which ls which python3
- Explanation:
ls
: Shows the full path to thels
executable (e.g.,/usr/bin/ls
).
type
- Indicate How a Command Name Would Be Interpreted
- Purpose: Describes how a command name would be interpreted by the shell (e.g., as a built-in, alias, function, or external executable).
- Basic Usage:
type command_name
- Example with Arguments:
type cd type ls type ll # If 'll' is an alias
- Explanation:
cd
: Will likely show it as a shell built-in.ls
: Will likely show it as an executable in a specific path.ll
: If you've created an alias forll
, it will show the alias definition.
clear
- Clear the Terminal Screen
- Purpose: Clears the terminal screen, moving all previous output out of view.
- Basic Usage:
clear
- Example with Arguments:
clear
- Explanation:
- No arguments: Simply clears the screen.
Subscribe to my newsletter
Read articles from Divakar Chakali directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
