Mastering Linux From Beginner To Advanced
Mastering Linux From Beginner To Advanced
1
Linux file system hierarchy:
1. / (Root Directory)
2. /bin (Binaries)
• Contains essential binary executables (commands) needed by all users, including system
administrators.
• Commonly used commands like ls, cp, mv, rm, cat, echo, mkdir, and rmdir are stored here.
• These binaries are required for system recovery and are available in single-user mode.
2
4. /dev (Device Files)
• Stores system-wide configuration files and shell scripts used during system boot.
• Examples:
o /etc/passwd – User account details.
o /etc/shadow – Encrypted passwords.
o /etc/fstab – File system mount points.
o /etc/network/interfaces – Network configuration.
• Automatically mounts external storage devices like USB drives and CD-ROMs.
• Example:
o /media/usb/ – Mounted USB drive.
o /media/cdrom/ – Mounted CD/DVD.
3
10. /opt (Optional Software)
• Contains data for system services like web servers and FTP.
• Example:
o /srv/www/ – Web server files.
o /srv/ftp/ – FTP server files.
4
16. /tmp (Temporary Files)
5
Linux file Permissions:
Each file and directory in Linux have permissions associated with three categories:
When you run the ls -l command, you see file permissions in the following format:
Position Meaning
- File type (- for file, d for directory, l for link)
rwx Owner (User) permissions
r-x Group permissions
r-- Others permissions
6
Linux Shell Command Components:
Along with a Linux shell command, we can provide several additional elements to control its behavior
Below are the key components:
1. Arguments
• Arguments are values passed to a command to specify what it should operate on.
• Example:
cp file1.txt /home/user/
o cp is the command.
o file1.txt is the first argument (source file).
o /home/user/ is the second argument (destination directory).
2. Options (Flags)
ls -l --human-readable
3. Pipelines (|)
• Pipes allow the output of one command to be used as the input for another.
• Example:
ls -l | grep "test"
5. Environment Variables
echo $HOME
7
6. Command Substitution ($(), ````)
sleep 10 &
mkdir {dir1,dir2,dir3}
echo {1..5}
ls *.txt
ls file?.txt
ls file[1-3].txt
8
12. Shebang (#!)
#!/bin/bash
echo "This is a Bash script"
17. Aliases
9
18. Functions
myfunc() {
echo "Hello, $1"
}
myfunc Vishal # Prints 'Hello, Vishal'
10
Basics Linux Commands:
ls [OPTIONS] [DIRECTORY]
• Common Options:
• -l : Long listing format (shows details like permissions, ownership, size, and modification
time).
• -a : Displays hidden files (files starting with .).
• -h : Human-readable file sizes.
• -R : Recursively lists files in subdirectories.
• Example:
ls -lah /home/user
2. cd (Change Directory)
cd [DIRECTORY]
• Examples:
pwd
• Example:
11
4. mkdir (Make Directory)
• Common Options:
o -p : Creates parent directories if they do not exist.
• Example:
mkdir -p /home/user/new_folder/subfolder
rm [OPTIONS] FILE/DIRECTORY
• Common Options:
• Example:
6. rm -r devops/
• This command deletes the devops directory and all its contents recursively.
• Example:
rm -r devops/
rmdir DIRECTORY_NAME
• Example:
rmdir empty_folder
12
8. cat (Concatenate and Display File Contents)
• Example:
cat file.txt
zcat FILE.gz
• Example:
zcat archive.gz
• The touch command creates a new empty file or updates an existing file’s timestamp.
• Syntax:
touch FILE_NAME
• Example:
touch newfile.txt
• Example:
13
12. tail (View Last 10 Lines of a File)
• Example:
tail -f /var/log/syslog
• The less command allows you to view file contents one page at a time.
• Syntax:
less FILE
• Example:
less largefile.txt
• The more command allows you to view file contents but only scroll forward.
• Example:
more largefile.txt
• Example:
cp file1.txt /home/user/backup/
14
17. mv (Move or Rename Files and Directories)
mv oldname.txt newname.txt
ln -s /home/user/file.txt shortcut.txt
ln file.txt hardlink.txt
22. tee (Read from Standard Input and Write to File and Output)
• The tee command redirects output to both the screen and a file.
• Example:
ls | tee output.txt
sort file.txt
15
24. clear (Clear the Terminal Screen)
clear
• The diff command compares two files and highlights the differences.
• Example:
Login Commands:
• The ssh command is used to securely log into a remote machine over an encrypted
connection. It is commonly used for remote administration of servers.
• Syntax: (logs into example.com as 'user')
• Common Options:
16
CPU Management Commands:
1. lscpu
Displays detailed information about the CPU architecture, including the number of cores, threads,
model, and cache sizes.
Syntax:
lscpu [OPTIONS]
Common Options:
Example:
lscpu
2. nproc
Syntax:
nproc [OPTIONS]
Common Options:
• --all → Displays the total number of cores (including those that are offline).
Example:
nproc
nproc --all
17
3. top
Displays real-time information about CPU usage, memory, and running processes.
Syntax:
top [OPTIONS]
Common Options:
Example:
top
top -d 1
4. htop
An interactive and improved version of top with a better UI and sorting capabilities.
Syntax:
htop [OPTIONS]
Common Options:
Example:
htop
htop -u root
18
5. mpstat
Reports CPU usage for each processor core. Part of the sysstat package.
Syntax:
Common Options:
Example:
mpstat -P ALL 2 5
Displays CPU usage for all cores, refreshing every 2 seconds for 5 cycles.
6. iostat
Displays CPU and disk I/O statistics. Part of the sysstat package.
Syntax:
Common Options:
Example:
iostat -c 2 3
7. vmstat
Reports system performance metrics, including CPU usage, memory, and disk I/O.
Syntax:
Common Options:
19
Example:
vmstat 2 5
8. sar
Collects, reports, and saves CPU and system performance metrics. Part of the sysstat package.
Syntax:
Common Options:
Example:
sar -u 1 5
9. taskset
Syntax:
Common Options:
Example:
20
10. chrt
Syntax:
Common Options:
Example:
chrt -r 50 ./my_program
chrt -p 30 1234
11. nice
Syntax:
Common Options:
Example:
nice -n -5 my_script.sh
21
12. renice
Syntax:
Common Options:
Example:
22
Disk Management Commands:
• The df command displays information about disk space usage on file systems.
• The -h flag makes the output human-readable by showing sizes in KB, MB, or GB.
• Common Options:
df -h
2. du (Disk Usage)
• The du command estimates and displays the disk usage of files and directories.
• Syntax:
du [options] [file/directory]
• Common Options:
• Example:
• The free command provides information about system memory usage, including RAM and
swap.
• Syntax:
free [options]
• Common Options:
• -h: Human-readable format
• -g: Displays output in GB
• -s <seconds>: Refreshes output at a specified interval
• Example: (shows memory usage in MB)
free -m
23
2. vmstat (Virtual Memory Statistics)
• The vmstat command provides information about system performance, including memory,
CPU, and disk activity.
• Syntax:
vmstat [interval] [count]
• Common Options:
• -s: Displays memory statistics
• -d: Shows disk statistics
• -t: Includes timestamps
• Example: (updates stats every 5 seconds, 10 times)
vmstat 5 10
• The cat /proc/meminfo command displays detailed memory usage statistics from the /proc
file system.
• Syntax: (outputs detailed memory usage stats)
cat /proc/meminfo
• The slabtop command provides a real-time view of memory usage by kernel slabs.
• Syntax:
Slabtop (displays detailed memory slab information)
• Common Options:
• -t: Shows totals
• -k: Displays values in KB
• Example: (shows memory usage with process names and total memory usage)
smem -tk
24
Process related Commands:
1. ps (Process Status)
ps [options]
• Common Options:
• -e: Displays all processes
• -f: Full format listing
• -u <user>: Shows processes for a specific user
• -o <format>: Customizes the output format
• Example: (shows detailed information about all processes)
ps aux
• The top command provides a real-time view of system processes, CPU, and memory usage.
• Syntax:
top [options]
• Common Options:
• -o <field>: Sorts by a specified field
• -d <seconds>: Refresh interval
• -n <count>: Displays output a fixed number of times
• Example: (opens an interactive process monitor)
top
• The fuser command identifies processes that are using a specified file or socket.
• Syntax:
• Common Options:
• -k: Kills the processes using the file
• -m: Shows processes using a mounted file system
• Example:
25
4. kill (Terminate Processes)
• The kill command is used to terminate processes using their process ID (PID).
• Syntax:
• Common Options:
• -9: Force kill the process
• -15: Gracefully terminate the process (default)
• -l: List all signal names
• Example: (forcefully terminates process with PID 1234)
kill -9 1234
• The nohup command allows a process to continue running even after logging out.
• Syntax:
26
System Level commands:
1. uname
• The uname command is used to display system information such as the kernel name,
version, and hardware details. It is useful for checking system architecture and OS details.
• Syntax:
uname [OPTION]
• Common Options:
• Example:
uname -a
2. uptime
• The uptime command is used to check how long the system has been running. It also
provides the number of active users and system load averages.
• Syntax:
uptime
• Common Options:
• Example:
uptime -p
3. date
• The date command is used to display or set the system date and time. It allows formatting
and manipulating date values.
• Syntax:
27
• Common Options:
• Example:
4. who
• The who command shows a list of users currently logged into the system.
• Syntax:
who [OPTION]
• Common Options:
• Example:
who -q
5. whoami
• The whoami command prints the username of the currently logged-in user.
• Syntax:
whoami
6. which
• The which command locates the executable path of a given command. It is useful for finding
out where a command is installed.
• Syntax:
which [COMMAND]
• Example:
which python3
28
7. id
• The id command prints user and group IDs for a given user.
• Syntax:
id [OPTION] [USERNAME]
• Common Options:
• Example:
id
8. sudo
• The sudo command allows a permitted user to execute a command as another user, typically
as root.
• Syntax:
sudo [COMMAND]
• Example:
9. shutdown
• The shutdown command is used to power off or restart the system safely.
• Syntax:
• Common Options:
• -h : Halts the system (shutdown).
• -r : Reboots the system.
• now : Executes shutdown immediately.
• Example:
10. reboot
sudo reboot
29
11. apt
• The apt command is a package management tool for Debian-based distributions, used for
installing, updating, and removing software packages.
• Syntax:
• Common Commands:
• Example:
12. yum
• The yum (Yellowdog Updater, Modified) command is used for package management in
RHEL-based Linux distributions. It allows users to install, update, and remove packages.
• Syntax:
• Common Commands:
13. rpm
• The rpm (Red Hat Package Manager) command is used for managing .rpm packages on
RHEL-based systems.
• Syntax:
• Common Options:
30
• -U : Upgrades an existing package.
14. dnf
• The dnf (Dandified YUM) command is the next-generation package manager for Fedora and
RHEL-based distributions.
• Syntax:
• Common Commands:
15. pacman
• The pacman command is the package manager for Arch Linux and its derivatives.
• Syntax:
• Common Options:
31
16. portage
• The portage system is the package manager for Gentoo Linux, managed through the emerge
command.
• Syntax:
• Common Options:
32
User and Group Management Commands:
1. sudo
• The sudo (Super User Do) command allows a permitted user to execute a command as the
superuser (root) or another user, as specified in the /etc/sudoers file. It is commonly used
for executing administrative tasks that require elevated privileges.
• Syntax:
• Common Options:
2. useradd
The useradd command is used to create a new user account in a Linux system. It modifies the system
account files to add a new user. The user's home directory and other attributes can be customized
using various options.
• Syntax:
• Common Options:
• Example: Creates a user 'john' with a home directory, bash shell, and adds to 'developers'
group
3. whoami
• The whoami command displays the username of the currently logged-in user. It is useful for
verifying which user account is being used in a terminal session.
• Example: Outputs the current username
whoami
33
4. su
• The su (Substitute User) command allows switching to another user account without logging
out. If no username is specified, it defaults to switching to the root user.
• Syntax:
su [OPTIONS] [USERNAME]
• Common Options:
su - vishal
5. passwd
• The passwd command is used to change the password of a user account. It can also be used
by the root user to change passwords for other users.
• Syntax:
• Common Options:
passwd vishal
6. userdel
• The userdel command is used to delete a user account from the system. It removes the
user's account but does not delete their home directory by default.
• Syntax:
• Common Options:
userdel -r vishal
34
7. usermod
• The usermod command is used to modify an existing user account in a Linux system. It
allows changing the user's details such as group membership, login shell, and home
directory.
• Syntax:
• Common Options:
o -c [comment] → Adds or modifies the user’s description.
o -d [directory] → Changes the user's home directory.
o -m → Moves the user's files to the new home directory.
o -G [group] → Adds the user to a supplementary group.
o -aG [group] → Appends the user to a new group without removing them from
existing groups.
o -s [shell] → Changes the user’s login shell.
o -L → Locks the user account.
o -U → Unlocks the user account.
8. groupadd
• The groupadd command is used to create a new group in the system. Groups are used to
manage permissions for multiple users efficiently.
• Syntax:
• Common Options:
groupadd developers
35
9. gpasswd
• The gpasswd -a command is used to add a user to a specific group. It modifies the
/etc/group file.
• The gpasswd -d command is used to remove a user from a specific group.
• Syntax:
10. gpasswd -m
11. groupdel
• The groupdel command is used to remove a group from the system. It deletes the group but
does not affect users who were part of it.
• Syntax:
groupdel GROUPNAME
groupdel developers
36
File Permission Commands:
1. umask
• The umask (User File Creation Mode Mask) command sets default permissions for newly
created files and directories. It determines which permission bits should be masked
(disabled) by default. The umask value is subtracted from the system's default permissions
(usually 666 for files and 777 for directories) to determine the final permission set.
• Syntax:
• Common Options:
• Example:
umask 022 # Sets default permissions to 755 for directories and 644 for files
umask # Displays the current umask value
2. ls -l
• The ls -l command lists files and directories in long format, displaying detailed information
including permissions, ownership, size, and modification date.
• Syntax:
ls -l [OPTIONS] [FILE/DIRECTORY]
• Common Options:
• Example:
ls -l /home/user # Lists all files and directories in the home folder with details
ls -lah # Lists all files including hidden ones in human-readable format
37
3. chmod
• The chmod (Change Mode) command is used to change the permissions of files and
directories. It can modify read (r), write (w), and execute (x) permissions for the owner,
group, and others.
• Syntax:
• Common Options:
• Example:
4. chown
• The chown (Change Owner) command changes the ownership of files and directories,
allowing you to assign a new owner or group.
• Syntax:
• Common Options:
• Example:
38
5. chgrp
• The chgrp (Change Group) command changes the group ownership of a file or directory.
• Syntax:
• Common Options:
• Example:
39
File Compression Commands:
1. zip
• The zip command is used to compress files or directories into a .zip archive. It reduces the
file size to save disk space or makes it easier to transfer multiple files together.
• Syntax
• Common Options
2. gunzip
• The gunzip command is used to decompress files that have been compressed using the gzip
command. It works by removing the .gz extension and restoring the original file.
• Syntax
• Common Options
• -c: Write the decompressed data to standard output instead of replacing the original file.
• -d: Force decompression (useful for compressed .zip files).
• -f: Force decompression even if the file is already decompressed.
gunzip file.gz
3. gzip
• The gzip command is used to compress files in .gz format. It is typically used to reduce the
size of files for storage or transmission.
• Syntax
• Common Options
40
• -1 to -9: Set the compression level, where -1 is the fastest and -9 is the best
compression.
gzip file.txt
4. tar
• The tar command is used to create, modify, and extract .tar archives. It is commonly used for
packaging files together, often used in backup processes.
• Syntax
• Common Options
5. untar
• The untar command is essentially the process of extracting files from a .tar archive, often
used as a synonym for the tar -x command.
• Syntax
• Common Options
41
File Transfer Commands:
1. scp
• The scp (secure copy) command is used to securely transfer files between two systems over
a network. It uses SSH for data transfer, ensuring that the data is encrypted during transit.
• Syntax
• Common Options
• Example
To copy a file file.txt from your local system to a remote system
scp file.txt user@remote_host:/path/to/destination/
scp -i "c:\Users\Vishal\Downloads\linux-for-devops.pem"
c:\Users\Vishal\Downloads\linux-for-devops.pem ubuntu@ec2-15-27-22-
252.ap-south-1.compute.amazonaws.com:/home/ubuntu/keys
scp -i "c:\Users\Vishal\Downloads\linux-for-devops.pem"
c:\Users\Vishal\Downloads\2025\* [email protected]
1.compute.amazonaws.com:/home/ubuntu/keys
42
2. rsync
• The rsync command is used for fast and efficient file copying and synchronization between
two locations. It can be used locally or remotely and can handle incremental file transfers,
ensuring that only changes are copied, which speeds up subsequent syncs.
• Syntax
• Common Options
• Example
To synchronize the contents of the docs directory to a remote system
rsync -av docs/ user@remote_host:/path/to/destination/
43
Network Management Commands:
1. ping
The ping command is used to test the connectivity between a local machine and a remote host by
sending ICMP (Internet Control Message Protocol) echo request packets and measuring the response
time. It helps diagnose network issues such as packet loss and latency.
Syntax:
Common Options:
Example:
ping -c 4 google.com
This sends 4 ICMP echo requests to google.com and displays the response time.
2. netstat
The netstat command displays network connections, routing tables, interface statistics, masquerade
connections, and multicast memberships. It is useful for troubleshooting network issues and
monitoring active connections.
Syntax:
netstat [options]
Common Options:
Example:
netstat -tulnp
This displays all active listening TCP and UDP ports along with the process IDs.
44
3. ifconfig
The ifconfig command is used to configure, manage, and display network interface parameters in
Linux. It is commonly used for checking IP addresses, setting up network interfaces, and
enabling/disabling them.
Syntax:
Common Options:
Example:
ifconfig eth0
4. traceroute
The traceroute command tracks the route packets take to reach a network destination. It helps
diagnose network latency and routing issues by displaying each hop along the path.
Syntax:
Common Options:
Example:
traceroute google.com
45
5. tracepath
The tracepath command traces the path to a remote host, similar to traceroute, but does not
require root privileges. It provides MTU discovery along with hop information.
Syntax:
Common Options:
Example:
tracepath google.com
The mtr command is a combination of ping and traceroute, providing real-time network diagnostic
information.
Syntax:
Common Options:
Example:
mtr -r google.com
46
7. nslookup
The nslookup command queries DNS servers to obtain domain name or IP address mapping
information.
Syntax:
Common Options:
Example:
nslookup google.com
8. telnet
Telnet is a command-line network protocol used for interactive text-based communication with a
remote host over a TCP/IP network. It provides a way to connect to remote systems and issue
commands as if you were physically present on that machine. Telnet operates on port 23 by default
and does not encrypt the transmitted data, making it vulnerable to security threats. Due to its lack of
encryption, Telnet has largely been replaced by SSH for secure remote access.
Syntax:
Common Options:
Example:
telnet 192.168.1.1 23
47
9. hostname
The hostname command is used to display or set the system's hostname, which is the label assigned
to a machine on a network. Hostnames help identify devices in a networked environment and can be
used to configure DNS settings. This command is useful for checking the hostname of a machine and
modifying it as needed.
Syntax:
hostname [option]
Common Options:
Example:
hostname -I
10. ip
The ip command is a powerful tool used to manage network interfaces, configure IP addresses,
modify routing tables, and view detailed network information. It is a modern replacement for the
older ifconfig command.
Syntax:
Common Options:
Example:
ip addr show
48
11. iwconfig
The iwconfig command is used to configure wireless network interfaces, allowing users to set
parameters such as SSID, mode, frequency, and encryption type for Wi-Fi connections. Unlike
ifconfig, which manages wired connections, iwconfig is specific to wireless networks.
Syntax:
Common Options:
Example:
12. ss
The ss command is a modern replacement for netstat and is used to display socket connection
details. It provides information about active TCP, UDP, and raw sockets, making it useful for network
troubleshooting and performance monitoring.
Syntax:
ss [options]
Common Options:
Example:
ss -tulnp
This command shows all active listening ports along with the process details.
49
13. arp
The arp (Address Resolution Protocol) command is used to view and manipulate the ARP table,
which maps IP addresses to MAC addresses. ARP is essential for communication within a local
network as it resolves IP addresses to physical hardware addresses.
Syntax:
arp [options]
Common Options:
Example:
arp -a
14. dig
The dig (Domain Information Groper) command is used to query DNS name servers and retrieve
information about domain names. It is widely used for troubleshooting DNS-related issues.
Syntax:
Common Options:
Example:
dig google.com
50
15. nc (netcat)
The nc (Netcat) command is a versatile networking tool used for reading and writing data over
network connections using TCP or UDP. It can be used for port scanning, file transfer, or even setting
up simple network-based chat applications.
Syntax:
Common Options:
Example:
nc -v -z 192.168.1.1 80
16. whois
The whois command is used to query information about domain names, IP addresses, and
autonomous systems. It retrieves data from the WHOIS database, which contains information like
the domain owner, the registrar, and the registration date.
Syntax:
Common Options:
Example:
whois example.com
This command will fetch WHOIS information for the domain example.com.
51
17. ifplugstatus
The ifplugstatus command is used to check whether a network interface is plugged in or not. It is
commonly used on systems with network interfaces to determine if the cable is physically connected
to the network.
Syntax:
ifplugstatus [interface]
Common Options:
Example:
ifplugstatus eth0
This command will check if the eth0 interface is connected to the network.
18. iptables
iptables is a powerful command-line tool used for configuring the Linux kernel firewall. It enables
users to set up rules for traffic filtering, network address translation (NAT), and more. It is primarily
used to secure Linux-based systems.
Syntax:
Common Options:
Example:
This command appends a rule to allow incoming TCP traffic on port 80 (HTTP) to the INPUT chain.
52
19. nmap
The nmap command is a network exploration and security auditing tool. It is used to scan networks,
discover hosts and services, and identify open ports. It can also be used for security assessment by
detecting vulnerabilities in a network.
Syntax:
Common Options:
Example:
This command performs a ping scan on the entire subnet 192.168.1.0/24 to discover live hosts.
20. route
The route command is used to display or manipulate the IP routing table in Linux. It helps configure
the paths that network traffic takes to reach destinations, set up static routes, and troubleshoot
network issues.
Syntax:
route [OPTION]
Common Options:
Example:
route -n
53
Web Requests Commands:
1. curl
The curl command is a tool for transferring data to or from a server using various protocols like
HTTP, FTP, and more. It is commonly used for interacting with APIs, downloading files, and sending
data over the network.
Syntax:
Common Options:
• -O: Save the output to a file with the same name as the remote file.
• -L: Follow redirects.
• -X: Specify the HTTP method to use (e.g., -X GET, -X POST).
• -d DATA: Send data in the body of the request (used with POST).
• -H "Header: Value": Add headers to the request.
Example:
curl -O https://example.com/file.txt
This command will download the file from the URL https://example.com/file.txt and save it with the
same name.
2. jq
jq is a lightweight and flexible command-line JSON processor. It is used for parsing, filtering, and
modifying JSON data. It can handle large JSON datasets and is useful for working with APIs that
return JSON responses.
Syntax:
Common Options:
Example:
This command fetches JSON data from the API and filters the value of the name field.
54
3. wget
The wget command is used to download files from the web. It supports multiple protocols like HTTP,
HTTPS, and FTP. Unlike curl, wget is designed to download entire websites or files with more
advanced options like recursive downloading and resuming interrupted downloads.
Syntax:
Common Options:
Example:
This command downloads the file from the URL https://example.com/file.txt and saves it as file.txt.
4. watch
The watch command is used to execute a program periodically, displaying the output in the terminal.
It is often used to monitor the real-time output of a command, such as the status of a process,
system resource usage, or the contents of a file.
Syntax:
Common Options:
Example:
watch -n 5 df -h
This command runs the df -h command every 5 seconds to show disk space usage in a human-
readable format.
55
Text Processing & Manipulation Commands:
1. awk
awk is a powerful text processing tool used for pattern scanning, processing, and reporting. It is
commonly used to extract, manipulate, and analyze text from structured data such as logs, CSV files,
and reports. It operates on a line-by-line basis and divides each line into fields.
Syntax:
Common Options:
Example:
This command prints the first and third column of each line in file.txt.
2. sed
sed (Stream Editor) is used for text manipulation and transformation. It reads input line by line,
applies operations such as search, replace, insert, and delete, and outputs the modified text. It is
commonly used for batch editing in scripts.
Syntax:
Common Options:
Example:
56
3. grep
grep (Global Regular Expression Print) is used to search for specific patterns in files or output
streams. It scans line-by-line and prints matching lines based on the given pattern.
Syntax:
Common Options:
• -i – Case-insensitive search.
• -v – Invert match (show lines that do not match).
• -r – Recursively search in directories.
• -n – Show line numbers of matches.
• -E – Use extended regular expressions.
Example:
57
Log Analysis & Monitoring Commands:
1. Journalctl:
Syntax:
journalctl [OPTIONS]
Common Options:
Example: Shows logs for the nginx service from the last hour.
2. dmesg
Syntax:
dmesg [OPTIONS]
Common Options:
• -H – Human-readable format.
• -T – Show timestamps.
• -w – Follow logs in real time.
3. logrotate
logrotate is used for managing log files by rotating, compressing, and deleting old logs automatically.
Syntax:
Common Options:
58
• -v – Verbose mode (displays detailed output).
• --log [LOGFILE] – Write logrotate's output to a specified log file.
logrotate -d /etc/logrotate.conf
4. stat
Syntax:
stat FILE
stat /var/log/syslog
5. find: find is used to locate log files based on size, modification time, or name.
Syntax:
Common Options:
Syntax:
Common Options:
Example: Extracts the first and fifth column from system logs.
59
Linux Volume Management:
1. fdisk
fdisk is used to create, delete, and manipulate disk partitions on MBR (Master Boot Record)
partitioned disks.
Syntax:
Common Options:
Example:
fdisk /dev/sdb
2. parted
parted is an alternative to fdisk, used to manage partitions, particularly for GPT (GUID Partition
Table) disks.
Syntax:
Common Options:
Example:
60
3. mkfs
Syntax:
Common Options:
Example:
4. mount
Syntax:
Common Options:
Example:
5. umount
Syntax:
Example:
umount /mnt
61
6. lsblk
lsblk lists information about block devices, including disks and partitions.
Syntax:
lsblk [OPTIONS]
Common Options:
Example:
lsblk -f
7. blkid
blkid retrieves information about block devices, such as UUIDs and file system types.
Syntax:
blkid DEVICE
Example:
blkid /dev/sdb1
8. pvcreate
Syntax:
pvcreate DEVICE
Example:
pvcreate /dev/sdb1
62
9. pvs
Syntax:
pvs
10. vgcreate
Syntax:
Example:
11. vgs
Syntax:
vgs
12. lvcreate
Syntax:
Common Options:
Example:
63
Creates a 10GB logical volume named my_lv in the my_vg volume group.
13. lvs
Syntax:
lvs
14. lvextend
Syntax:
Example:
15. resize2fs
resize2fs resizes an ext-based file system to match the new size of a logical volume.
Syntax:
Common Options:
Example:
resize2fs /dev/my_vg/my_lv
64
16. lvremove
Syntax:
lvremove LV_PATH
Example:
lvremove /dev/my_vg/my_lv
17. vgremove
Syntax:
vgremove VG_NAME
Example:
vgremove my_vg
18. pvremove
Syntax:
pvremove DEVICE
Example:
pvremove /dev/sdb1
65
19. df
Syntax:
df [OPTIONS]
Common Options:
• -h – Human-readable format.
• -T – Show file system type.
Example:
df -h
20. du
Syntax:
du [OPTIONS] FILE/DIRECTORY
Common Options:
• -h – Human-readable format.
• -s – Display total size only.
Example:
du -sh /var/log
66
Service Management Commands:
1. systemctl
The systemctl command is used to manage system services in Linux. It interacts with the systemd
service manager to start, stop, restart, enable, disable, and check the status of services. It is commonly
used in modern Linux distributions.
Syntax:
systemctl [OPTIONS] COMMAND SERVICE_NAME
Common Options
Example:
systemctl start nginx
67
Linux documentation commands:
1. help
The help command in Linux provides built-in documentation for shell commands that are not
standalone binaries but are instead shell built-ins. These built-ins are commands integrated into the
shell itself (like cd, echo, exit, etc.), and help allows users to quickly access their syntax, available
options, and usage details.
Unlike man or info, which provide documentation for external programs, help is used specifically for
shell built-in commands. It is mainly used in Bash and some other shells that support built-in command
documentation.
Syntax:
help [OPTION] [BUILTIN_COMMAND]
Common Options:
Examples:
2. man
The man (manual) command is used to display the user manual for commands and programs in Linux.
It provides detailed documentation, including command usage, options, and descriptions. The manual
is divided into multiple sections, such as general commands, system calls, and library functions.
Syntax:
man [SECTION] command_name
Common Options:
68
Examples:
3. info
The info command is another documentation tool that provides more detailed and structured
information compared to man. It presents information in a node-based, navigable format, often with
hyperlinks to related topics.
Syntax:
info [command_name]
Common Options:
Examples:
4. whatis
The whatis command provides a brief, one-line description of a command, similar to using man -f. It
quickly helps users understand the purpose of a command without opening the full manual.
Syntax:
whatis command_name
Examples:
whatis mkdir # Displays a one-line summary like "mkdir (1) - make directories".
whatis tar # Find out what tar does
69
5. apropos
The apropos command searches the manual pages for a keyword, similar to man -k, and helps users
find relevant commands based on functionality.
Syntax:
apropos keyword
Examples:
Summary of Differences
70
Shell Scripting:
1. echo
The echo command is used to display a line of text or a variable value on the terminal. It is
commonly used in shell scripts to provide output messages to users.
Syntax:
Common Options:
Example:
2. read
The read command is used to take user input from the terminal. It waits for the user to enter input
and stores it in a variable.
Syntax:
Common Options:
Example:
71
3. if Statement
The if statement is used to execute a block of commands conditionally. It is useful for decision-
making in scripts.
Syntax:
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
Example:
num=10
if [ $num -gt 5 ]; then
echo "Number is greater than 5"
else
echo "Number is 5 or less"
fi
4. for Loop
The for loop is used to iterate over a sequence of values. It simplifies repetitive tasks.
Syntax:
Example:
for i in 1 2 3 4 5; do
echo "Iteration: $i"
done
72
5. while Loop: The while loop repeatedly executes a block of commands as long as a condition is
true.
Syntax:
while [ condition ]; do
commands
done
Example:
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
6. case Statement: The case statement is used for pattern matching and is an alternative to
multiple if-elif conditions.
Syntax:
case variable in
pattern1)
commands ;;
pattern2)
commands ;;
*)
default commands ;;
esac
Example:
7. function in Shell Script: Functions in shell scripting allow you to define reusable blocks of code.
Syntax:
function_name() {
commands
}
Example:
hello() {
echo "Hello, World!"
}
hello
73
Vim Editor Commands and Shortcuts:
Vim is a powerful text editor used in Linux. To open a file in Vim, use the following command.
Syntax:
vim filename
Vim starts in Normal mode. To insert text, you need to switch to Insert mode.
Syntax:
Command Description
i Insert before cursor
I Insert at beginning of line
a Append after cursor
A Append at end of line
o Open a new line below cursor
O Open a new line above cursor
Once editing is done, you can save and exit Vim using different commands.
Syntax:
Command Description
:w Save file
:q Quit Vim
:wq Save and quit
:x Save and quit (only if changes were made)
:q! Quit without saving
74
Common Options & Examples:
Syntax:
Command Description
h Move left
l Move right
j Move down
k Move up
0 Move to beginning of line
^ Move to first non-blank character of line
$ Move to end of line
gg Move to the beginning of file
G Move to the end of file
:n Move to line n
You can search for specific text in a file using the following commands.
Syntax:
Command Description
/pattern Search forward for 'pattern'
?pattern Search backward for 'pattern'
n Repeat the last search in the same direction
N Repeat the last search in the opposite direction
75
6. Copy, Cut, and Paste (Yank, Delete, and Put)
To copy, cut, and paste text in Vim, use the following commands in Normal mode.
Syntax:
Command Description
yy Copy current line
yw Copy current word
y$ Copy from cursor to end of line
dd Cut (delete) current line
dw Cut current word
d$ Cut from cursor to end of line
p Paste after cursor
P Paste before cursor
Syntax:
Command Description
u Undo last change
U Undo all changes on current line
Ctrl + r Redo the last undone change
76
8. Replacing and Substituting Text
You can replace characters or substitute text using the following commands.
Syntax:
Command Description
r<char> Replace current character with <char>
R Enter Replace mode
:s/old/new/ Replace 'old' with 'new' on the current line
:%s/old/new/g Replace 'old' with 'new' globally in the file
Syntax:
Command Description
v Start visual mode
V Start visual line mode
Ctrl + v Start visual block mode
Syntax:
Command Description
:split Split window horizontally
:vsplit Split window vertically
Ctrl + w + w Switch between windows
Ctrl + w + q Close current window
77
Common Options & Examples:
Syntax:
Command Description
x Delete character under cursor
X Delete character before cursor
dw Delete current word
d$ Delete from cursor to end of line
dd Delete current line
D Delete from cursor to end of line (same as d$)
dG Delete from cursor to end of file
dgg Delete from cursor to beginning of file
12. Indentation
Syntax:
Command Description
>> Indent current line right
<< Indent current line left
5>> Indent 5 lines right
5<< Indent 5 lines left
= Auto-indent current line
=% Auto-indent matching braces block
78
13. Working with Buffers
Syntax:
Command Description
:e filename Open file in a new buffer
:ls List all open buffers
:bnext or :bn Move to next buffer
:bprevious or :bp Move to previous buffer
:bd Close current buffer
Syntax:
Command Description
:split filename Split window horizontally and open file
:vsplit filename Split window vertically and open file
Ctrl + w + w Switch between windows
Ctrl + w + q Close current window
Ctrl + w + h/j/k/l Move between split windows
79
15. Macros (Recording and Replaying Commands): Vim allows recording keystrokes as macros for
automation.
Syntax:
Command Description
q<register> Start recording to register <register>
q Stop recording
@<register> Replay macro stored in <register>
@@ Replay last used macro
16. Working with Marks: Marks allow bookmarking positions in a file for quick navigation.
Syntax:
Command Description
ma Set mark 'a' at cursor position
``a` Move cursor to mark 'a'
'a Move cursor to start of line where mark 'a' is
:marks List all marks
:delmarks a Delete mark 'a'
Syntax:
Command Description
:set spell Enable spell checking
:set nospell Disable spell checking
]s Move to next misspelled word
[s Move to previous misspelled word
z= Suggest correct spelling for misspelled word
80