0% found this document useful (0 votes)
6 views45 pages

Unix RHCSA Notes

The document serves as a comprehensive reference guide for Unix/Linux and RHCSA, covering foundational topics such as the history and architecture of Unix and Linux, key features, and virtual machines. It details the Linux boot process, filesystem structure, essential commands for navigation, file operations, and text processing. Additionally, it includes information on file types, links, and searching for files, making it a valuable resource for system administration and management.

Uploaded by

Ashwini Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views45 pages

Unix RHCSA Notes

The document serves as a comprehensive reference guide for Unix/Linux and RHCSA, covering foundational topics such as the history and architecture of Unix and Linux, key features, and virtual machines. It details the Linux boot process, filesystem structure, essential commands for navigation, file operations, and text processing. Additionally, it includes information on file types, links, and searching for files, making it a valuable resource for system administration and management.

Uploaded by

Ashwini Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unix / Linux

& RHCSA Reference Guide


Foundations • Commands • Scripting • Administration
Part I – Foundations
1. History of Unix & Linux
Unix
Unix was created by Dennis Ritchie and Ken Thompson at AT&T's Bell Laboratories in 1969, written in the C programming
language. It became the foundation for nearly all modern operating systems.

Linux
Linux was created by Linus Torvalds in 1991 — the name combines "Linus" and "Unix". It is open-source, meaning anyone
can use, modify, and distribute it freely.

Linux Distributions
Distributions (distros) package the Linux kernel with software tools, desktop environments, and libraries. Examples:
Ubuntu, Debian, Fedora, CentOS, Red Hat Enterprise Linux (RHEL).

2. Linux Architecture
The Linux system has four concentric layers:
• Hardware – physical components (CPU, RAM, disks, NICs).
• Kernel – heart of the OS; manages hardware, memory, scheduling, I/O. One kernel runs for all users.
• Shell – command interpreter bridging user and kernel. Multiple shells run simultaneously (one per user).
• Tools & Applications – user-facing programs interacting through the shell.

Kernel Functions
• Manages files and data transfers
• Allocates and manages memory
• Schedules programs and allocates CPU time via timer interrupts (time-slices)
• Handles hardware interrupts

Shell Types
Shell Description

Bash (Bourne Again Shell) Default on most Linux distros; powerful and widely used.

sh (Bourne Shell) Original Unix shell; simpler and less powerful.

Zsh (Z Shell) Advanced shell with auto-completion and plugins.

Ksh (Korn Shell) Combines features of Bash and C shell.

Tcsh Enhanced C shell with scripting features.


echo $0 # show current default shell

3. Key Features of Linux


Feature Description

Open Source Free to use, modify, and distribute.


Multi-user Multiple users work simultaneously without interfering with each other.

Multitasking Runs multiple processes concurrently via CPU time-slices.

Security Strong file permissions, user authentication, and file encryption.

Stability Rarely crashes; preferred for servers with high uptime requirements.

Portability Runs on almost any hardware platform.

CLI Powerful command-line interface for system management and automation.

Package Management Easy installation and updating of software.

Networking Built-in tools for robust network setup and troubleshooting.

Developer Friendly Ships with compilers, libraries, and scripting tools.

4. Virtual Machines
A Virtual Machine (VM) is a software-based emulation of a physical computer, allowing you to run a full OS as if on separate
hardware.

Key Components
• Host Machine – the physical computer running the VM.
• Guest Machine – the virtual machine itself.
• Hypervisor – software creating and managing VMs, allocating shared hardware resources.

Hypervisor Types
Type Description Examples

Type 1 – Bare Metal Runs directly on hardware; no underlying OS. VMware ESXi, Microsoft Hyper-V, Xen

Type 2 – Hosted Runs on top of an existing OS. VirtualBox, VMware Workstation


Part II – Boot Process
5. Linux Boot Sequence: BIOS → MBR → GRUB → Kernel → SystemD
Stage 1 – BIOS / UEFI
• First program executed, stored in read-only memory on the motherboard.
• Performs POST (Power-On Self-Test) to verify hardware.
• Detects bootable devices (HDD, USB, CD) and passes control to MBR.
• Modern systems use UEFI (Unified Extensible Firmware Interface) instead.

Stage 2 – MBR (Master Boot Record)


• First 512 bytes of any bootable device, split into three sections:
◦ Boot loader – 446 bytes
◦ Partition Table – 64 bytes
◦ Error Checking (Magic Number) – 2 bytes
• Loads the boot loader into memory and passes control.

Stage 3 – GRUB (Grand Unified Bootloader)


• Loads /boot/grub2/[Link] at boot time.
• Presents a menu to select OS or kernel version.
• Locates the kernel binary: /boot/vmlinuz-<kernel-version>
• Loads kernel and initrd/initramfs image into memory, then passes control.
NOTE: RHEL7 default boot loader is GRUB2 (x86). Intel Itanium uses ELILO.

Stage 4 – Kernel
• initramfs decompresses and loads a temporary root filesystem.
• Detects and loads hardware drivers from the temporary filesystem.
• Mounts the real root filesystem (including LVM, RAID partitions).
• Initialises the first process: SystemD (PID 1).
/boot/vmlinuz-<version> # kernel binary
/boot/[Link]-<version> # initial RAM disk

Stage 5 – SystemD
• Always PID 1 — the first process started.
• Starts all required services and brings the system to its configured target.
Runlevel (SysV) systemd Target Meaning

0 [Link] Halt / Shutdown

1 [Link] Single-user / rescue mode

3 [Link] Multi-user CLI (no GUI)

5 [Link] Multi-user with GUI

6 [Link] Reboot
/etc/systemd/system/[Link] # configured default target
/usr/lib/systemd/system # all target unit files
Part III – The Filesystem
6. Linux Directory Structure (FHS)
The Unix/Linux filesystem resembles an inverted tree. Everything starts from root /. There are no drive letters — all devices
mount into this single hierarchy.

Directory Purpose

/ Root – single starting point of the entire filesystem.

/bin User Binaries – essential commands: ls, cp, grep, ping, ps. Available in single-user mode.

/sbin System Binaries – admin commands: iptables, reboot, fdisk, ifconfig, swapon.

/etc Configuration Files – all program configs and startup/shutdown scripts.

/dev Device Files – terminals, USB drives, disks appear as files here.

/proc Process Info – virtual filesystem; /proc/{pid} per-process info; /proc/cpuinfo, /proc/meminfo.

/var Variable Data – grows over time: logs (/var/log), mail, spool, temp across reboots.

/tmp Temporary Files – cleared automatically on every reboot.

/usr Unix System Resources – binaries (/usr/bin), admin binaries (/usr/sbin), libraries (/usr/lib).

/home Home Directories – personal space for each user (e.g. /home/ashwini).

/root Root User Home – private home directory of root (NOT the same as /).

/boot Boot Files – kernel, initrd image, GRUB configuration.

/lib /lib64 System Libraries – ld* and lib*.so.* files supporting /bin and /sbin.

/opt Optional Software – third-party or vendor-installed applications.

/mnt Mount Point – temporary mount directory used by sysadmins.

/media Removable Media – auto-mount point for USB drives, CD-ROMs.

/srv Service Data – server-specific data (e.g. /srv/cvs for CVS).

/run Runtime Data – transient state files (PIDs, lock files); recreated fresh every boot.

7. Files, Types, Inodes & Links


File Types (first character in ls -l)
Symbol File Type Notes

- Regular file Text files, images, scripts, binaries.

d Directory A folder holding other files.

l Symbolic (soft) link A shortcut pointing to another file or directory.

b Block device Read/write in blocks (e.g. hard drives). Usually in /dev.

c Character device Transmits data character by character (e.g. keyboard, terminal). Usually in /dev.

p Named pipe (FIFO) Inter-process communication; First In First Out.

s Socket Communication between processes (e.g. network services).


ls -l Output Format
Example: drwxr-xr-x 2 shiva shiva 4096 Sep 11 22:22 Desktop

Field Meaning

d File type character.

rwxr-xr-x Permissions: [user rwx][group rwx][others rwx]

2 Number of hard links.

shiva shiva Owner name and group name.

4096 File size in bytes.

Sep 11 22:22 Last modification timestamp.

Desktop File or directory name.

NOTE: "total 40" at top of ls = total disk blocks used. Each block = 1024 bytes.

Hidden Files & Special Entries


• Files starting with . are hidden (e.g. .bashrc, .profile). Use ls -a to see them.
• . = current directory; .. = parent directory. Both are auto-created in every new directory.

Inode
An inode is a data structure storing metadata about a file: permissions, owner, size, timestamps, and pointers to data
blocks. The filename itself lives in the directory entry, not the inode.
ls -li filename # show inode number
find /home -inum NUMBER # find file by inode number

Hard Links vs Symbolic Links


Feature Hard Link Symbolic (Soft) Link

Points to Same inode (same data on disk). Path/name of the target file.

If original deleted Link still valid — data preserved. Link breaks (dangling link).

Cross-filesystem No. Yes.

Link to directory Not allowed (usually). Allowed.

Create command ln file linkname ln -s file linkname


ln file1 file2 # hard link
ln -s [Link] [Link] # symbolic link

NOTE: Hard links share the same inode number. Use ls -li to verify both names point to the same inode.

File Colours in ls
Colour Meaning

Blue Directory

Green Executable file

Cyan / Light Blue Symbolic link


Yellow on black Device file (/dev/sda)

Magenta / Pink Image file (.jpg, .png)

Red Archive or compressed file (.tar, .zip, .gz)

White / Default Regular file (.txt, .log)

Red text on background Broken symbolic link (dangling)

8. Filesystem Types
Filesystem Strengths Best For

EXT4 Stable; performs well across varied file sizes. General-purpose Linux servers.
Default on many distros.

XFS Optimised for large files and high-throughput Databases, large storage, enterprise servers.
parallel workloads.

tmpfs RAM-based; very fast; contents lost on reboot. Used for /run and /tmp.

vfat Cross-platform (Windows-compatible). USB drives, removable media.


df -TH # show filesystem type for all mounted filesystems

Interview Tip: XFS vs EXT4: XFS handles large files and parallel I/O better; EXT4 is general-purpose. Common interview
comparison.
Part IV – Essential Commands
9. Navigation & Identity
Command Description

pwd Print working directory – show current location.

cd /path Change to absolute path.

cd .. Go one directory level up.

cd - Switch to previous working directory.

cd or cd ~ Return to home directory.

whoami Show current logged-in username.

who Show all logged-in users with terminal and login time.
w Extended who – includes load average and idle time.

last Show recent login history.

id username Show UID, GID, and all group memberships.

hostname Show system hostname.

date Show system date and time.

date +%D Date only (MM/DD/YY).

date +%T Time only (HH:MM:SS).

cal / cal July 2025 Display calendar.

uptime Show how long the server has been running and load averages.

NOTE: Absolute path starts with / (e.g. /home/ashwini/Unix). Relative path does not (e.g. cd Unix from inside
/home/ashwini).

10. Listing Files – ls


Command / Option Description

ls List files and directories.

ls -l Long format: permissions, links, owner, group, size, date, name.

ls -ltr Long format sorted by modification time (-t), reversed (-r) – oldest first.

ls -a Show all files including hidden (names starting with .).

ls -i Show inode numbers alongside filenames.

lc Display files in columnar layout.

lf Mark executables with * and directories with /.

Wildcards in ls
Pattern What it Matches

ls *.txt All .txt files.


ls file? file followed by exactly one character.

ls [aeiou]* Files starting with a vowel.

ls [!aeiou]* Files NOT starting with a vowel.

ls [a-m][c-z][4-9]?? Complex range: 1st char a-m, 2nd c-z, 3rd 4-9, then any 2 chars.

touch file{1..5} Create file1, file2, file3, file4, file5 at once.

11. File Operations


Command Description

touch filename Create empty file (or update timestamps if it exists).

cat file Display entire file content.

cat > file Create file and type content; Ctrl+D to save.

cat f1 f2 > f3 Concatenate f1 and f2 into f3 (overwrites f3).

cat f1 f2 >> f3 Append f1 and f2 to f3 (keeps existing content).

cp src dst Copy file. Creates dst if not exists; overwrites if exists.

cp f1 f2 /dir Copy multiple files to a directory.

mv file /dest Move (cut-paste) a file.

mv fileA fileNew Rename a file.

mv OldDir NewDir Rename a directory.

rm filename Delete a file.

rm -i file Delete with confirmation prompt (-i = interactive).

rm -rf dir Recursively delete directory and all contents. -f forces without prompt.

head -5 file Display first 5 lines.

tail -5 file Display last 5 lines.

less file Interactive scroll. /word to search; n=next; gg=first line; G=last line.

more file View file page by page (forward only).

wc -l file Count number of lines.

cmp fileA fileB Check if two files are identical.

diff -u fileA fileB Show line-by-line differences.

split -l 3 file Split file into parts of 3 lines each.

shuf file Randomly shuffle lines.

truncate -s 100M file Extend or shrink a file to the specified size.

12. Directory Commands


Command Description

mkdir dirname Create a directory.


mkdir -p a/b/c Create nested directories including all parents in one command.

mkdir -m 754 dir Create directory with specific permissions (bypasses umask).

rmdir dirname Remove an empty directory.

rm -rf dirname Remove directory and ALL contents recursively.

13. Finding Files


find – Real-Time Search
Option Description

find ./ -name "[Link]" Search by exact name from current directory.

-iname Case-insensitive name match.

-type f / -type d Filter by type: f=file, d=dir, l=symlink, b=block, s=socket.


-size +1M -size -50M Files between 1 MB and 50 MB. M=MB, K=KB, G=GB, c=bytes.

-mtime 15 Files modified exactly 15 days ago.

-mmin 30 Files modified 30 minutes ago.

-user shiva / -group devs Owned by specific user or group.

-inum NUMBER Find by inode number (get it from ls -li).

-perm 777 Files with exact permission 777.

-empty Empty files or directories.

-exec rm {} \; Run command on each found file. {} = filename, \; ends exec.

-delete Delete matching files directly (use with caution!).

-maxdepth 2 / -mindepth 1 Control depth of directory traversal.

-newer [Link] Files newer than [Link].

-prune Exclude directories from search.

locate – Cache-Based Fast Search


updatedb # update the file database cache (run as root)
locate filename # fast name-based search from cached database

NOTE: Newly created files will not appear in locate results until updatedb is run.
Part V – Text Processing
14. grep – Search Inside Files
grep = Globally search a Regular Expression and Print. Searches for patterns in files line by line.
grep "word" file # basic search
grep -i "word" file # case-insensitive
grep -r "word" /path/ # recursive through directories
egrep "word1|word2" file # match multiple words (OR logic)

Option Description

-i Ignore case.

-r or -R Recursive search through all files in a directory.

-n Show line numbers with matches.

-v Invert match – show lines that do NOT match.

-l List only filenames containing matches.

-f pattern_file Get patterns from a file, match against another file.

-c Count matching lines.

-w Match whole words only.

-x Match entire line.

-e Specify multiple patterns: grep -e "A" -e "B" file

^pattern Lines starting with pattern.

pattern$ Lines ending with pattern.

-q Quiet mode – no output; used in scripts (check $?).

-s Suppress error messages.

--color=auto Highlight matching text in colour.

-h Suppress filenames from multi-file output.

Tool Specialty

grep Basic regular expression.

egrep Extended regex – supports | without escaping. Better: egrep "Kara|merry" file

fgrep Fixed string – no regex. Use for literal special characters like *.

rgrep Recursive search.

zgrep Search inside .gz compressed files.

pgrep Search for running processes by name.

pdfgrep Search inside PDF files.

NOTE: echo $? after grep: 0 = match found, 1 = no match. Useful for conditional scripting.

15. sed – Stream Editor


sed processes text line by line. Key symbols: s = substitute, g = global (all occurrences), d = delete, p = print, a = append, i =
insert.

Command Description

sed 's/old/new/' file Replace first occurrence per line.

sed 's/old/new/g' file Replace ALL occurrences.

sed -i 's/old/new/g' file Save changes directly to file.

sed -[Link] 's/old/new/g' file Save changes; create .bak backup (best practice in production).

sed 's/p1/p2/g' f > [Link] Without -i: redirect changed output to new file.

sed -n '5p' file Print line 5 only.

sed -n '5,10p' file Print lines 5 to 10.

sed -n '$p' file Print last line.

sed '5d' file Delete line 5.

sed '/^$/d' file Delete empty lines (^ start, $ end with nothing between = blank line).

sed '/error/d' file Delete lines containing "error".

sed '3a New line here' file Insert a new line AFTER line 3.

sed '3i New line here' file Insert a new line BEFORE line 3.

sed '5s/Tom/Adam/' file Replace only on line 5.

sed -e 's/A/B/' -e 's/C/D/' Multiple commands with -e.


file

Interview Tip: Without -i, sed shows output on screen — file is unchanged. With -i, file is updated directly. Use -[Link] in
production to keep a backup.

16. awk – Column & Pattern Processing


awk reads files line by line and processes them by field. -F sets the field separator.
awk -F, '{print $2}' [Link] # column 2 (comma-separated)
awk -F , '{print $1,$3,$NF}' file # col 1, col 3, and last col
awk '/Fabes/ {print}' [Link] # search for word
echo "Hello Tom" | awk '{$2="Adam"; print $0}' # replace word
awk 'length($0) > 15' [Link] # lines longer than 15 chars
awk 'NR==5' [Link] # print specific line number 5
ls -l | awk '{print NF}' # count columns in ls output

Variable Meaning

$0 Entire line.

$1 First field.

$2 Second field.

$NF Last field (N-th Field).

NR Current line number.

NF Total number of fields in the current line.

17. cut – Extract Specific Columns


cut -c1-2 [Link] # characters 1 to 2 per line
cut -c1-5 [Link] # first 5 characters
cut -c1,3,5 [Link] # specific characters 1, 3, and 5
cut -b1-3 [Link] # extract by byte position
cut -d: -f5 /etc/passwd # delimiter ":" field 5 (description field)

NOTE: For /etc/passwd: ashwini:x:1000:1000:Ashwini Kumar:/home/ashwini:/bin/bash — cut -d: -f5 extracts "Ashwini
Kumar".

18. tr, sort & uniq


Command Description

sort file Sort file content alphabetically.

sort -r file Sort in reverse order.

sort file | uniq Show unique lines (must be sorted first for uniq to work).

uniq -c Prefix each line with count of occurrences.

uniq -d Print only duplicate lines.

tr [:lower:] [:upper:] < Convert lowercase to uppercase.


file

tr -d / < file Delete all / characters.

tr "/" "%" < file Replace / with %.

19. I/O Redirection, Pipes, tee & xargs


Redirection Symbols
Symbol Meaning Example

> Redirect stdout to file ls > [Link]


(overwrite).

>> Redirect stdout to file (append). echo "hi" >> [Link]

< Redirect stdin from a file. wc -l < [Link]

2> Redirect stderr to file. cmd 2> [Link]

2>> Redirect stderr (append). cmd 2>> [Link]

&> Redirect both stdout and stderr. cmd &> [Link]

2>&1 Redirect stderr to same cmd > [Link] 2>&1


destination as stdout.

File Descriptor Stream

0 stdin (keyboard input)

1 stdout (normal output)

2 stderr (error output)

Pipe |
Sends the output of one command as input to the next.
ps -ef | grep java # find java processes
ls -ltr | grep ".txt" # list text files
sort file | uniq # sort then get unique lines

tee
Reads stdin and writes to BOTH stdout AND a file simultaneously.
ls -ltr | tee [Link] # shows output AND saves to file
ls | tee [Link] | wc -l # count lines while also saving to file

NOTE: ls > [Link] | wc -l returns 0 because > redirects all output before wc can count it. tee solves this by splitting the
stream.

xargs
Converts stdin output into arguments for commands that don't accept stdin directly.
ls | xargs echo "hi" # hi [Link] [Link] ...
find . -name "*.tmp" | xargs rm # delete all .tmp files

20. Wildcards & Regex


Wildcard Meaning Example

* Zero or more characters. ls *.txt

? Exactly one character. ls file?.txt

[abc] One character from the ls file[12].txt


set.

[a-z] Any character in range. ls file[a-c].txt

[^abc] Any character NOT in the ls file[^1].txt


set.

{} Comma-separated or touch file{1..5}


range patterns.

~ Home directory. cd ~/Documents


grep -E '\b[0-9]{4}-[0-9]{2}-[0-9]{2}\b' [Link] # match YYYY-MM-DD
# \b = word boundary, {4} = exactly 4 digits, {2} = exactly 2 digits

NOTE: Wildcards are interpreted by the shell before the command runs (shell globbing), not by the command itself.
Part VI – vi / vim Editor
vi is the standard Unix text editor available on every Linux/Unix system. vim (Vi IMproved) is the enhanced version. Three
modes: Normal (navigation), Insert (typing), Visual (selection). Always press Esc before issuing commands.
vi filename # open or create file
nano filename # simpler alternative

21. Mode Switching


Key Mode & Action

Esc Return to Normal mode (always press first before commands).

i Insert mode – insert before cursor.

a Insert mode – append after cursor.

I Insert mode – insert at start of line.

A Insert mode – append at end of line.

o Insert mode – open new line below.

O Insert mode – open new line above.

22. Save & Quit


Command Description

:w Save (write) file.

:q Quit (only if no unsaved changes).

:wq or ZZ Save and quit.

:q! Force quit WITHOUT saving (discard changes).

:e! Undo ALL changes – reload file from disk.

23. Navigation
Key Action

h/l Move left / right.

j/k Move down / up.

0 Jump to start of line.

^ Jump to first non-blank character.

$ Jump to end of line.

gg Go to first line of file.

G Go to last line of file.

:n Go to line number n.

w Jump to next word.


b Jump to previous word.

24. Editing
Command Description

x Delete character under cursor.

dd Delete (cut) current line.

4dd Delete 4 lines.

D Delete from cursor to end of line.

yy or Y Yank (copy) current line.

p / P Paste below / above cursor.

u Undo last change.

Ctrl+r Redo.

r<char> Replace character under cursor.

:set nu / :set nonu Show / hide line numbers.

:syntax on Enable syntax highlighting.

:%s/word/newword/g Replace a word globally across the entire file.

25. Search & Multi-file


Command Description

/word Search forward for "word". n = next match; N = previous.

?word Search backward.

vi -o f1 f2 Open two files side by side; Ctrl+W twice to switch between them.

vi -d f1 f2 Diff-compare two files side by side.

v / V Visual mode – character-wise / line-wise selection.


Part VII – Permissions & Security
26. File Permissions
Every file and directory has three permission sets: User/Owner (u), Group (g), Others (o). Each set has Read (r=4), Write
(w=2), Execute (x=1).
Example output: drwxr-xr-x = d (directory), rwx (user has all), r-x (group can read+execute), r-x (others can read+execute).

Permission Symbol Numeric Value

Read r 4

Write w 2

Execute x 1

No permission - 0

chmod – Change Permissions


chmod 755 file # numeric: rwxr-xr-x
chmod a+rwx file # symbolic: add rwx for all
chmod go+x file # add execute to group and others
chmod go+r,go-w file # add read, remove write from g and o
chmod go=r,u=rw file # set exact permissions (removes unspecified)
chmod u+s file # set SUID bit
chmod g+s dir # set SGID bit
chmod +t dir # set sticky bit

Directory Permissions Matrix


Permission cd (enter) ls (list) cp into cp from

r-- No Yes No No

-w- No No No No

--x Yes No No No

rw- No Yes No No

r-x Yes Yes No Yes

-wx Yes No Yes No

rwx Yes Yes Yes Yes

Interview Tip: Best directory permission: 754 (rwxr-xr--). Gives owner full control, group read+enter, others read only.

27. umask
umask (user file creation mask) defines which permissions to DENY when new files or directories are created.
umask # display current umask (default 0022)
umask 234 # change umask for the current session

umask Value New File New Directory

0022 644 (rw-r--r--) 755 (rwxr-xr-x)

0002 664 (rw-rw-r--) 775 (rwxrwxr-x)


0077 600 (rw-------) 700 (rwx------)

28. Special Permission Bits


Bit Applies To Purpose Numeric

SUID (setuid) Files File runs with the owner's privileges instead of the 4xxx
caller's.

SGID (setgid) Files & Dirs Files: run with group privilege. Dirs: new files inherit 2xxx
parent group.

Sticky Bit Directories Only the file owner (or root) can delete their own files 1xxx
inside.
chmod 4755 file # SUID + rwxr-xr-x
chmod 2755 dir # SGID + rwxr-xr-x
chmod 1777 dir # Sticky bit + rwxrwxrwx

# Verify: sticky bit shows as t at the end:


drwxrwxrwt 2 user group 50 Sep 25 mydir

NOTE: Sticky bit on a binary file keeps it in RAM after execution for faster re-use (requires superuser). Example:
/usr/bin/vi

29. chown & chgrp


chown root [Link] # change owner to root
chown user:group filename # change owner and group together
chgrp paul [Link] # change group only
chgrp -R superheroes dir/ # change group recursively

30. Access Control Lists (ACL)


ACL gives fine-grained permissions beyond user/group/others — without changing base ownership. Commands: setfacl and
getfacl.
getfacl filename # view ACL entries
setfacl -m u:ashwini:rwx /path/file # add user permission (-m = modify)
setfacl -m g:devteam:rx /path/file # add group permission
setfacl -x u:ashwini /path/file # remove specific user entry
setfacl -b filename # remove ALL ACL entries
setfacl -Rm "u:ashwini:rwx" dir/ # apply recursively

NOTE: Files with ACL show + in ls -l output: -rw-rw-r--+ 1 paul paul 0 Jun 11 file1
Part VIII – User & Group Management
31. Key System Files
File Contents & Format

/etc/passwd User accounts. Format: username:x:UID:GID:description:home_dir:shell

/etc/shadow Encrypted passwords + password aging data. Readable by root only.

/etc/group Group definitions. Format: groupname:x:GID:member1,member2


grep ashwini /etc/passwd
# ashwini:x:1000:1000:Ashwini Kumar:/home/ashwini:/bin/bash
# Fields: name : password(x) : UID : GID : description : home : shell

32. User Management


Command Description

useradd username Create user with defaults.

useradd -g group -s /bin/bash Create with group, shell, description, and home directory.
-c "desc" -m -d /home/u
username

passwd username Set or change user password.

userdel username Delete user (home directory kept).

userdel -r username Delete user AND home directory.

id username Show UID, GID, and all group memberships.

chage -l username Show password aging info for a user.

chage -m 5 -M 90 -W 10 -I 3 Set min(-m) / max(-M) days, warn(-W), inactive(-I).


user
# Example: create full user
useradd -g superheroes -s /bin/bash -c "Ironman Character" -m -d /home/ironman ironman
passwd ironman

33. usermod & Group Management


usermod -G superheroes spiderman # set supplementary group (REPLACES all existing
groups)
usermod -aG avengers spiderman # APPEND group (keeps existing memberships)
groupadd groupname # create a group
groupdel groupname # delete a group
cat /etc/group # list all groups

Option Meaning

-G Set supplementary groups — replaces current group list.

-aG Append — keeps all existing group memberships.

NOTE: Always use -aG in production to avoid accidentally removing a user from groups they need.
34. /etc/[Link] – Default Password Policy
Controls system-wide defaults for user account management. Used by useradd, passwd, and chage.

Setting Description

PASS_MAX_DAYS 90 Password expires after 90 days.

PASS_MIN_DAYS 0 Minimum days before password can be changed.

PASS_WARN_AGE 7 Warn user 7 days before expiry.

UID_MIN 1000 Regular users start from UID 1000.

UID_MAX 60000 Maximum UID for regular users.

SYS_UID_MIN 201 System users range: 201–999.

UMASK 022 Default permission mask for new files.

CREATE_HOME yes Auto-create home directory on useradd.

Interview Tip: "Where are password aging defaults defined?" → /etc/[Link]. "Where is actual password data
stored?" → /etc/shadow.

35. su, sudo & visudo


Command Description

su username Switch to another user – asks that user's password.

su - username Switch with full login environment (PATH, profile, etc.) loaded.

su - oracle Switch to oracle user (common in production support work).

sudo command Run command as root using YOUR own password – more secure.

sudo -u oracle command Run command as a specific other user.

visudo Safely edit /etc/sudoers – validates syntax before saving.


# Example /etc/sudoers entries (always edit via visudo):
ashwini ALL=(ALL) ALL # full sudo access
ashwini ALL=(ALL) /usr/bin/systemctl restart httpd # restricted to one command

NOTE: NEVER edit /etc/sudoers directly. Always use visudo. A broken sudoers file disables sudo system-wide.
Interview Tip: su has no audit trail and requires sharing the target user's password. sudo logs every command and uses
individual passwords — always preferred in enterprise environments like TCS.

36. User Communication Commands


Command Description

users Show all users currently logged in.

wall "System reboot in 5 Broadcast a message to ALL logged-in users.


min"

write username Send a message to one specific user (type message, then Ctrl+D to send).

37. Centralised Account Systems


Term Type Description

Active Directory (AD) Microsoft Directory Service Manages users, computers, groups, policies in a Windows
domain via Kerberos authentication.

LDAP Protocol (not a product) Query users/groups/passwords — like SQL for directories. AD
uses LDAP internally.

IDM / FreeIPA Identity Management Create user once → access Linux, Windows, VPN, Email
System centrally.

WinBind (Samba) Linux-to-AD bridge Allows Linux servers to authenticate users via Active Directory.

OpenLDAP Open-source LDAP server Linux-only directory service for environments without AD.

SSSD / Realm Linux integration tools Connect Linux systems to AD or FreeIPA for centralised login.
Part IX – Process Management
38. Viewing Processes
Command Style Key Columns

ps -ef System V UID, PID, PPID, C, STIME, TTY, TIME, CMD – shows parent-child hierarchy.

ps aux BSD USER, PID, %CPU, %MEM, VSZ, RSS, TTY, STAT, START, TIME, COMMAND –
shows resource usage.

ps -u username User filter All processes belonging to a specific user.


ps -ef | grep java # check if java process is running
ps -ef | grep autosys # find autosys-related processes
pgrep crond # get PID of the cron daemon

top – Real-Time Monitoring


top auto-refreshes every few seconds showing real-time CPU, memory, and process data.

Key (while inside top) Action

P Sort processes by CPU usage.

M Sort by memory usage.

k Kill a process (enter PID when prompted).

r Renice – change priority of a process.

c Show full command path.

1 Show per-CPU usage (multi-core view).

q Quit top.

Interview Tip: Load Average in top: "2.00, 1.50, 1.00" = past 1 min, 5 min, 15 min averages. If load > number of CPU
cores, the system is overloaded.

39. Signals & kill


Signal Number Meaning

SIGTERM 15 Graceful stop – allows process to clean up (default kill).

SIGKILL 9 Force kill – immediate termination; no cleanup possible.

SIGHUP 1 Hang up – reload configuration (e.g. Apache, NGINX reload).

SIGINT 2 Interrupt – same as pressing Ctrl+C.

SIGSTOP 19 Pause process.

SIGCONT 18 Resume a paused process.

SIGQUIT 3 Quit with core dump.


kill PID # graceful kill (sends SIGTERM 15)
kill -15 PID # explicit SIGTERM
kill -9 PID # force kill – last resort only
pkill java # kill by process name
killall httpd # kill ALL instances of httpd
kill -l # list all available signals
Interview Tip: Always try graceful kill first. kill -9 does NOT allow memory cleanup, file handles to close, or DB
connections to terminate gracefully — can cause data corruption.

40. Job Control


Command Description

jobs Show all active background and stopped jobs.

Ctrl+Z Pause (suspend) the current foreground process.

bg Resume the most recently paused job in the background.

fg %1 Bring job number 1 to the foreground.

nohup ./script & Run in background; immune to SIGHUP when logging out.

nohup ./script Same, but discard output.


>/dev/null &

NOTE: nohup prevents the SIGHUP signal from reaching the process when you disconnect. Essential for long-running
production jobs.

41. Priority – nice & renice


CPU scheduling priority range: -20 (highest) to +19 (lowest). Default = 0. Only root can set negative values.
nice -n 10 [Link] # launch with lower priority (nice value 10)
nice -n -10 [Link] # higher priority (root only)
renice 10 -p 1234 # change priority of running process
ps -o pid,ni,cmd # view nice values of processes
Part X – Shell Scripting
42. Scripting Basics
A shell script is a set of commands that execute sequentially to automate tasks like file manipulation, program execution,
and system administration.
#!/bin/bash # shebang line – MUST be first line; tells OS which interpreter to use

# Run a script:
chmod +x [Link] # give execute permission first
./[Link] # run from current directory
bash [Link] # alternative – no execute permission needed
/full/path/to/[Link] # absolute path

# Single-line comment:
# This is a comment

# Multi-line comment:
<< comment
your comment here
comment

43. Variables
VAR_NAME=value # define variable (no spaces around =)
VAR_NAME=$(hostname) # command substitution – captures command output
echo $VAR_NAME # print variable ($ prefix required)
readonly var_name=123 # constant – cannot be changed after setting
a1=`hostname` # backtick syntax (older, equivalent to $())

Arrays
# Indexed Array:
myArray=( 1 2 Hello "Hey man" ) # define
echo "${myArray[0]}" # element at index 0
echo "${#myArray[*]}" # array length
echo "${myArray[*]:1:2}" # slice: start at 1, take 2 elements
myArray+=( 5 6 8 ) # append elements

# Associative (Key-Value) Array:


declare -A myArray
myArray=( [name]=Paul [age]=20 )
echo "${myArray[name]}"

String Operations
myVar="Hello World!"
length=${#myVar} # string length
upper=${myVar^^} # convert to UPPERCASE
lower=${myVar,,} # convert to lowercase
replace=${myVar/World/Buddy} # replace first occurrence
slice=${myVar:6:11} # substring: start at index 6, length 11

44. User Input & Arithmetic


read var_name # read input from user
read -p "Enter your name: " NAME # read with prompt

# Arithmetic – three methods:

# 1. $(( )) – Recommended:
sum=$((a+b))
echo $((a-b)) echo $((a*b)) echo $((a/b)) echo $((a%b))

# 2. (( )) – Increment/decrement:
((i++)) ((i--)) ((i+=2)) ((i*=3))

# 3. expr – Legacy (spaces required around operators):


sum=`expr $a + $b`

45. Conditionals
# if-else:
if [[ $score -gt 40 ]]
then
echo "Passed"
else
echo "Failed"
fi

# if-elif-else:
if [ $marks -ge 80 ]; then
echo "First Division"
elif [ $marks -ge 60 ]; then
echo "Second Division"
else
echo "Fail"
fi

Comparison Integer Operator String Operator

Equal -eq ==

Not Equal -ne !=

Greater Than -gt (n/a)

Greater Than or Equal -ge (n/a)

Less Than -lt (n/a)

Less Than or Equal -le (n/a)

NOTE: -eq is for integers; == is for string comparison. Mixing them causes unexpected results.
Operator Meaning

-e File exists.

-s File exists and is not empty.

-f File exists and is NOT a directory.

-d Directory exists.

-x File is executable.

-w File is writable.

-r File is readable.
if [ $? -eq 0 ]; then echo "Previous command succeeded"; fi
# $? = exit status of last command (0 = success, non-zero = failure)

case Statement
case $choice in
a) date ;;
b) ls ;;
*) echo "Not a valid option"
esac

Logical Operators
# AND – both conditions must be true:
if [[ $age -ge 18 ]] && [[ $country == "India" ]]; then echo "Please vote"; fi

# OR – at least one condition must be true:


if [[ $score -ge 50 ]] || [[ $vip == "yes" ]]; then echo "Access granted"; fi

46. Loops
# for loop – list:
for i in 1 2 3 4 5
do
echo "Number: $i"
done

# for loop – range:


for p in {1..20}; do echo $p; done

# for loop – read from file:


for item in $(cat /home/user/[Link]); do echo $item; done

# for loop – weekday counter:


for day in Mon Tue Wed Thu Fri
do echo "Weekday $((i++)) : $day"; done

# while loop:
i=1
while [ $i -le 5 ]
do
echo $i
((i++))
done

# Simulated do-while (runs at least once, then checks condition):


i=1
while true
do
echo $i
((i++))
if [ $i -gt 5 ]; then break; fi
done

NOTE: Bash has no built-in do-while loop. Simulate it with while true and a break condition at the end.

47. Script Arguments & Special Variables


Variable Meaning

$0 Script name / path.

$1, $2, ... First, second, ... arguments passed to the script.

$@ All arguments – each treated as a separate item (safe for loops).

$* All arguments – joined into one single string.

$# Total count of arguments passed.

$$ Current script PID.

$? Exit status of last command (0 = success).

$! PID of the last background process.


#!/bin/bash
echo "Script: $0"
echo "First arg: $1"
echo "Total args: $#"
echo "All args: $@"

# Run: ./[Link] red blue green


# Output: Script: ./[Link] First: red Total: 3 All: red blue green

Interview Tip: $@ vs $*: $@ treats each argument separately (correct for loops); $* joins all into one string (can break if
values contain spaces).
Part XI – Networking
48. Network Fundamentals
Client-Server Model
A client requests services or data; a server provides them. Example: Browser (client) → HTTP request → Web server
(Apache/NGINX) → HTTP response → Browser.

IP Addressing
Type Format Description

IPv4 [Link] 32-bit, written as 4 dot-separated octets. Most common.

IPv6 2001:0db8::8a2e:7334 128-bit. Created as IPv4 address pool ran out.

Subnet & CIDR Notation


A subnet divides a large network into smaller logical groups. The subnet mask defines which bits are network vs host.
IP: [Link]
Subnet Mask: [Link]
CIDR: [Link]/24 # /24 = 24 bits for network

Network addr: [Link]


First host: [Link]
Last host: [Link]
Broadcast: [Link]
Usable hosts: 254

Interview Tip: One-liner: An IP address identifies a device on a network; a subnet divides networks into smaller logical
groups to manage traffic efficiently.

Gateway
A gateway (usually a router) is the exit point for traffic leaving the local network. Same-subnet traffic goes directly; external
traffic routes through the gateway first.
ip route # view routing table / default gateway
route -n # alternative
# Example output: default via [Link] dev eth0

Static IP vs DHCP
Feature Static IP DHCP

Configuration Manual – set by admin. Automatic – assigned by DHCP server (often the router).

Address Changes No – fixed. Yes – leased for a time period.

Use Case Servers, printers, routers. Laptops, desktops, client devices.

Management Harder – manual tracking. Easier – centrally managed.

Network Interfaces & MAC Address


Interface Meaning
eth0 / ens33 Wired Ethernet interface.

wlan0 Wi-Fi (wireless) interface.

lo Loopback – always [Link]. Used for local testing.


MAC Address (Media Access Control): physical hardware address of a NIC — e.g. 00:1A:2B:3C:4D:5E. Unique; assigned by
the manufacturer. Works at Layer 2 (Data Link) of the network model.

49. Networking Commands


Command Description

ip addr / ifconfig Show IP addresses and network interfaces.

ip route Show routing table and default gateway.

ip link Show interface status (up/down, MAC).

ping [Link] Test network connectivity to a host.

telnet IP Port Test if a specific IP:Port is open and reachable.

netstat -putan | grep 80 Check if port 80 is open on local server.

ss -tuln Show listening ports – modern replacement for netstat.

ss -plant Show ports with process names.

traceroute [Link] Show all network hops (routers) to destination.

50. File Transfer


Windows ↔ Linux
Use WinSCP (graphical) for file transfers between Windows and Linux over SSH.
systemctl start [Link] # ensure SSH service is running
systemctl status [Link]

Linux ↔ Linux (SCP)


SCP (Secure Copy Protocol) transfers files securely over SSH.
# Local to Remote:
scp /local/file username@remote_host:/path/

# Remote to Local:
scp username@remote_host:/path/file /local_path

# Copy entire directory (-r flag):


scp -r /local/dir username@remote_host:/path/

Download & API


wget URL # download file
wget -O [Link] URL # save with custom filename
curl [Link] # call an API endpoint
Part XII – Package Management & Services
51. Package Management
Distro Family Package Manager Key Commands

RHEL / CentOS / Fedora yum / dnf / rpm yum install, dnf list installed, rpm -qa

Ubuntu / Debian apt apt install, apt search, dpkg -l

Command Description

sudo yum install nginx Install a package (RHEL/CentOS).

sudo apt install nginx Install a package (Ubuntu/Debian).

rpm -qa | grep app Check if an RPM package is installed.

dnf list installed List all installed packages.


apt search package Search available packages (Ubuntu).

yum list available List available packages (RHEL).

52. systemctl – Service Management


Command Description

systemctl status sshd Check status (running/stopped, PID, recent logs).

systemctl start httpd Start a service.

systemctl stop httpd Stop a service.

systemctl restart httpd Full restart (stop + start) – use after config changes.

systemctl reload httpd Reload config without full restart (smoother).

systemctl enable httpd Enable autostart at boot.

systemctl disable httpd Disable autostart.

systemctl is-active sshd Quick check: is it running?

systemctl is-enabled sshd Quick check: does it start at boot?

systemctl list-units -- List all services.


type=service --all

53. Environment Variables


Environment variables store configuration data: paths, user info, shell preferences.
printenv # list all environment variables
printenv HOME # show specific variable
echo $HOME # same result

MYVAR="hello" # set (current shell only)


echo $MYVAR
unset MYVAR # remove variable

export JAVA_HOME="/usr/lib/jvm/java_v" # export (available to child processes)


export PATH=$JAVA_HOME/bin:$PATH # prepend to existing PATH
Scope Method

Current shell only MYVAR="hello" (no export)

Current user – all shells Add to ~/.bash_profile or ~/.bashrc → then: source ~/.bashrc

All users – system-wide Add to /etc/profile → then: source /etc/profile


Part XIII – Job Scheduling
54. cron – Recurring Scheduler
cron is the background daemon (crond) that executes scheduled jobs. crontab is each user's job file.
# Crontab syntax:
# MIN HOUR DOM MON DOW command
# | | | | |-> Day of Week (0-7, 0 and 7 = Sunday)
# | | | |-----> Month (1-12)
# | | |---------> Day of Month (1-31)
# | |--------------> Hour (0-23)
# |------------------> Minute (0-59)

0 2 * * * /home/user/[Link] # daily at 2:00 AM


*/5 * * * * [Link] # every 5 minutes
0 3 * * 0 [Link] # every Sunday at 3:00 AM
0 9 1 * * [Link] # 1st of every month at 9 AM

Command Purpose

crontab -e Edit your cron jobs.

crontab -l List your cron jobs.

crontab -r Remove all your cron jobs.

crontab -u user -e Edit another user's cron jobs (root required).

systemctl status Check the cron service status.


crond

Shortcut Equivalent Cron Time

@reboot Run once at system startup.

@daily 00***

@weekly 00**0

@monthly 001**

@yearly 0011*

Location Purpose

/etc/crontab System-wide cron jobs.

/etc/[Link]/ Drop scripts here to run daily.

/etc/[Link]/ Drop scripts here to run hourly.

/etc/[Link]/ Drop scripts here to run weekly.

/etc/[Link]/ Drop scripts here to run monthly.

/var/spool/cron/ Individual user cron files.

55. anacron – Catch-Up Scheduler


anacron runs missed cron jobs after the system comes back online. Config: /etc/anacrontab.
# /etc/anacrontab format: days delay(min) job-id command
1 5 [Link] run-parts /etc/[Link]
7 10 [Link] run-parts /etc/[Link]
30 15 [Link] run-parts /etc/[Link]
# "daily" jobs run 5 min after boot if missed

Feature cron anacron

Execution Exact scheduled time. After next boot if the job was missed.

Requires system ON Yes. No.

Best for Servers (always on). Laptops and workstations.

Precision High. Low (runs on next boot after a delay).

56. at – One-Time Scheduling


at schedules a job to run ONCE at a specific time, then it's done. Unlike crontab which repeats.
at 5pm # schedule at 5 PM today (type commands, Ctrl+D to save)
at now + 10 minutes # run after 10 minutes
at 2am tomorrow # tomorrow at 2 AM
at 10:00 2026-03-01 # specific date

Command Description

atq List all pending at jobs.

atrm JOB_ID Remove a scheduled at job.

at -c JOB_ID Show commands in a scheduled job.

systemctl status Check the at daemon.


atd
Part XIV – System Monitoring
57. Memory
free -h # RAM and swap usage (human-readable)
free -th # include total row (RAM + swap combined)
cat /proc/meminfo # detailed raw memory statistics from the kernel

Column (free output) Meaning

total Total installed RAM.

used Memory currently in active use.

free Completely unused memory.

buff/cache Memory used for buffers and caching (can be freed under pressure).

available Actual RAM available right now (free + recoverable cache).

58. CPU & System Info


lscpu # CPU architecture, cores, threads, sockets
cat /proc/cpuinfo # detailed CPU hardware info from kernel
grep -c processor /proc/cpuinfo # count logical CPU cores
top # real-time CPU and process monitor

59. Disk
df -h # disk space per filesystem (human-readable)
df -kh # in kilobytes
df -TH # include filesystem type
du -sh myfolder/ # disk usage of a specific folder
lsblk # list block devices and partition layout

60. Kernel Logs & I/O


dmesg | less # kernel ring buffer (boot errors, hardware messages)
dmesg | grep -i error # filter for error messages
dmesg | grep -i usb # USB device detection
journalctl -p err # systemd journal – error-level entries
iostat -x 2 # CPU + disk I/O statistics (part of sysstat package)

Interview Tip: iostat is essential for diagnosing slow database or application servers — high iowait percentage indicates
a disk I/O bottleneck.

61. Log Files – /var/log


Log File Purpose

/var/log/messages General system log (RHEL/CentOS).

/var/log/syslog System activity log (Ubuntu/Debian).

/var/log/secure SSH logins, sudo usage, authentication (RHEL).


/var/log/[Link] Authentication log (Ubuntu).

/var/log/dmesg Kernel boot and hardware messages.

/var/log/cron Cron job execution log.

/var/log/httpd/ Apache web server access and error logs.

/var/log/nginx/ NGINX web server logs.

/var/log/[Link] Boot process messages.

62. Monitoring Quick Reference


Command Purpose

top Real-time CPU, memory, and process monitor.

free -h Quick RAM usage summary.

df -h Disk space per filesystem.

du -sh dir/ Disk usage of specific directory.

dmesg Kernel and boot logs.

iostat Disk I/O performance statistics.

ip addr Network interface configuration.

ss -tuln Open and listening ports.

cat /proc/cpuinfo CPU hardware details.

cat /proc/meminfo Detailed memory statistics.

lscpu CPU architecture and core info.

lsblk Block devices and partitions.

journalctl -p err System error messages.

tail -f Follow live log output.


/var/log/messages
Part XV – System Administration
63. Shutdown & Reboot
Command Description

shutdown -h now Immediate graceful shutdown (notifies users, stops services properly).

shutdown -r now Immediate graceful reboot.

shutdown -h +10 Shutdown in 10 minutes (warns all logged-in users).

reboot Restart system – equivalent to shutdown -r now.

halt Stop system (may not power off on older hardware).

init 0 / systemctl Power off (SysV legacy / modern systemd).


poweroff

init 6 / systemctl reboot Reboot.


systemctl isolate multi- Switch to multi-user CLI mode without reboot.
[Link]

Interview Tip: In production, use shutdown -h +5 to give users time to save work and allow transactions to complete
before shutdown.

64. Hostname Management


hostnamectl # view all hostname info
sudo hostnamectl set-hostname app-server01 # set permanent static hostname
sudo hostnamectl set-hostname "Production Server" --pretty # set human-readable name

Hostname Type Stored In Description

Static /etc/hostname Permanent hostname set by admin. Survives reboot.

Pretty /etc/machine-info Human-readable descriptive name.

Transient Runtime (memory) Temporary – usually assigned by DHCP. Not persistent.

65. System Information


Command Description

cat /etc/redhat-release Show RHEL version (e.g. Red Hat Enterprise Linux release 9.3).

cat /etc/os-release Show OS details – universal, works on all distros.

uname -a Full kernel and OS information.

uname -r Kernel version only.

uname -m Architecture (x86_64, aarch64, etc.).

arch CPU architecture type.

lscpu CPU, cores, threads, sockets, virtualisation support.

getconf LONG_BIT Check if system is 32-bit or 64-bit.

dmidecode -t system System hardware info from BIOS (root required).


dmidecode -t memory RAM slot details and capacity.

dmidecode -t bios BIOS version and release date.

66. sosreport – Diagnostic Collection


sosreport collects system configuration, logs, and diagnostic information into one compressed file for support teams to
analyse.
sudo sosreport
# Output saved to: /var/tmp/sosreport-<hostname>-<date>.[Link]

Collects: system logs (/var/log), running services, kernel info, hardware details, network configuration, and installed
packages.

67. tmux – Terminal Multiplexer


tmux runs multiple terminal sessions in one window and keeps processes running after you log out — more powerful than
screen.
sudo yum install tmux # RHEL/CentOS
sudo apt install tmux # Ubuntu

Command Description

tmux Start a new session.

tmux new -s backup Start a named session.

Ctrl+B then D Detach from session (session keeps running in background).

tmux ls List all active sessions.

tmux attach -t backup Reattach to a named session.

tmux kill-session -t Kill a session.


backup

Ctrl+B then " Split window horizontally.

Ctrl+B then % Split window vertically.

Ctrl+B then Arrow key Switch between panes.

Interview Tip: tmux is essential for long production jobs. Detach before logging off and reattach the next day — the
process keeps running uninterrupted.

68. Reset Root Password


1. Reboot the system.
2. Press Esc or Shift during boot to open the GRUB menu.
3. Select the Linux kernel and press e to edit boot parameters.
4. Find the line starting with linux or linux16. Append [Link] at the end. Press Ctrl+X to boot.
5. Remount the root filesystem read-write and change root:
mount -o remount,rw /sysroot
chroot /sysroot

6. Reset the root password:


passwd root

7. Fix SELinux context (critical on RHEL/CentOS — skip this and the system may fail to boot):
touch /.autorelabel

8. Exit and reboot:


exit
reboot

69. Filesystem Repair – fsck


Steps to Troubleshoot a Corrupted Filesystem:
9. Check system logs for errors:
dmesg | grep -i error
journalctl -p err
# Look for: EXT4-fs error, I/O error, Filesystem corrupted

10. Identify the affected partition:


df -h
mount
# Check for any filesystem showing as read-only

11. Unmount the filesystem (must be unmounted before repair):


umount /dev/sdb1
# If busy:
lsof | grep /dev/sdb1
fuser -m /dev/sdb1

12. Run filesystem check and repair:


fsck /dev/sdb1 # interactive repair
fsck -y /dev/sdb1 # auto-fix all errors
fsck -fy /dev/sdb1 # force check + auto-fix all errors

13. Remount and verify:


mount /dev/sdb1 /data
df -h

14. If the ROOT filesystem is corrupted, boot into rescue mode, then:
fsck /dev/sda1 # root filesystem cannot be checked while it is mounted

15. Check physical disk health:


smartctl -a /dev/sda
# Look for: reallocated sectors, pending sectors, hardware failure warnings

NOTE: GOLDEN RULE: Never run fsck on a mounted filesystem — except the root filesystem in rescue/single-user mode.
Part XVI – Utilities & Miscellaneous
70. Compression & Archiving
Feature tar gzip

Function Archiving – bundles multiple files into one. Compression – reduces file size.

Extension .tar .gz

Compresses? No (archives only). Yes (single file only).

Preserves metadata? Yes. No.

Common use Combine multiple files/directories. Shrink a single file.

Command Description

gzip -k file Compress file; -k keeps the original.


gzip -d file / gunzip Decompress a .gz file.
file

tar -czf [Link] dir/ Archive + compress a folder. c=create, z=gzip, f=file.

tar -xzf [Link] Extract + decompress. x=extract, z=gzip, f=file.

zip [Link] f1 f2 Zip multiple files together.

unzip -l [Link] List files inside a zip archive.

71. Aliases
Aliases create shortcuts for long or frequently used commands, saving time and reducing errors.
alias l='ls -ltr' # create alias
alias -p # list all existing aliases
unalias l # remove alias

Scope Where to Add

Current shell only Run alias command in terminal.


(temporary)

Current user permanently Add to ~/.bashrc → then: source ~/.bashrc

All users (system-wide) Add to /etc/bashrc

72. Terminal Keyboard Shortcuts


Shortcut Action

Ctrl + A Go to start of the line.

Ctrl + E Go to end of the line.

Ctrl + U Cut everything before the cursor.

Ctrl + K Cut everything after the cursor.

Ctrl + W Cut one word before cursor.


Ctrl + Y Paste the last cut text.

Ctrl + L Clear terminal screen (same as clear command).

Ctrl + R Reverse search through command history.

Ctrl + C Cancel / kill current running process.

Ctrl + G Abort a reverse search (Ctrl+R).

Ctrl + D Exit session / End-of-file (EOF).

Ctrl + Z Pause (suspend) current foreground process.

Alt + B Move cursor backward one word.

Alt + F Move cursor forward one word.

73. Utility Commands


Command Description

history Show previously used commands.

!N Re-run command number N from history.

echo $? Show exit status of last command (0=success, non-zero=failure).

command --help Show usage options for a command.

man command Read the full manual page.

which command Show the full path of the executable.

bc Command-line calculator.

script Record all terminal activity to a file (exit to stop).

su username Switch to another user account.

exit / Ctrl+D Exit current session / EOF.

echo "ABCDE" | fold -w1 Display characters vertically, one per line.

ssh user@host Connect to a remote Linux server over SSH.

scp file user@host:/tmp/ Securely copy file to remote server.

74. Password Encryption (Kali Linux)


echo '12345' | openssl passwd -1 stdin > [Link] # encrypt
john [Link] # decrypt (John the Ripper)

NOTE: The more complex the password, the longer it takes John the Ripper to crack. Used in security testing and
penetration testing.
Appendix – Quick Command Reference (115 Commands)
Consolidated reference of all commands covered in this guide.

# Command Category Purpose

1 pwd Navigation Show current directory.

2 cd /path Navigation Change to absolute path.

3 cd .. Navigation Go one level up.

4 cd - Navigation Switch to previous directory.

5 whoami Identity Current logged-in user.

6 who Identity All logged-in users.

7 w Identity Extended who with load avg.

8 id user Identity Show UID, GID, groups.

9 hostname System System hostname.

10 date System Date and time.

11 uptime System Server uptime.

12 uname -a System Full OS / kernel info.

13 arch System CPU architecture.

14 lscpu System CPU details and core count.

15 lsblk System List disk partitions.

16 cat /etc/os-release System OS version info.

17 ls -ltr Files List files sorted by time.

18 ls -a Files Show hidden files.

19 ls -i Files Show inode numbers.

20 touch file Files Create empty file.

21 cat file Files Display file content.

22 less file Files Scroll through file.

23 head -5 file Files First 5 lines.

24 tail -5 file Files Last 5 lines.

25 wc -l file Files Count lines.

26 cp src dst Files Copy file.

27 mv file dest Files Move or rename.

28 rm file Files Delete file.

29 rm -rf dir Files Delete directory recursively.

30 cmp f1 f2 Files Compare files byte-by-byte.

31 diff -u f1 f2 Files Show file differences.


32 split -l 3 file Files Split into 3-line chunks.

33 shuf file Files Shuffle lines randomly.

34 truncate -s 100M f Files Resize file.

35 mkdir dir Dirs Create directory.

36 mkdir -p a/b/c Dirs Create nested directories.

37 rmdir dir Dirs Remove empty directory.

38 find / -name f Search Real-time file search.

39 locate file Search Cache-based file search.

40 updatedb Search Update locate cache.

41 grep "w" file Text Search in file.

42 egrep "a|b" file Text Extended regex search.

43 sed -i s/a/b/ file Text In-place find & replace.

44 awk -F, {print $2} Text Extract column from CSV.

45 cut -c1-5 file Text Extract characters 1–5.

46 sort file Text Sort content.

47 sort | uniq Text Show unique lines.

48 tr lower upper Text Translate characters.

49 chmod 755 file Perms Set permissions.

50 chown user file Perms Change owner.

51 chgrp grp file Perms Change group.

52 umask Perms Show/set default mask.

53 getfacl file ACL View ACL.

54 setfacl -m u:u:rwx ACL Set ACL permission.

55 ln f1 f2 Links Create hard link.

56 ln -s orig link Links Create symbolic link.

57 ps -ef Processes List processes (SysV).

58 ps aux Processes List processes (BSD).

59 pgrep name Processes Get PID by name.

60 top Processes Real-time process monitor.

61 kill PID Processes Graceful stop (SIGTERM).

62 kill -9 PID Processes Force kill (SIGKILL).

63 pkill name Processes Kill by process name.

64 killall name Processes Kill all instances.

65 jobs Jobs Show background jobs.

66 bg Jobs Resume in background.


67 fg Jobs Bring to foreground.

68 nohup ./s & Jobs Run without hangup.

69 nice -n 10 s Priority Launch with lower priority.

70 renice 10 -p PID Priority Change running priority.

71 free -h Memory RAM usage summary.

72 cat /proc/meminfo Memory Detailed memory stats.

73 df -h Disk Filesystem disk space.

74 du -sh dir/ Disk Directory size.

75 dmesg | less Logs Kernel messages.

76 iostat -x 2 I/O Disk I/O stats.

77 journalctl -p err Logs System error entries.

78 ip addr Network IP addresses.

79 ip route Network Routing table.

80 ss -tuln Network Listening ports.

81 ping host Network Test connectivity.

82 telnet IP Port Network Test IP:port.

83 traceroute host Network Show network hops.

84 scp file u@h:/ Transfer Secure file copy.

85 wget URL Download Download a file.

86 curl URL Download API / web request.

87 yum install pkg Packages Install (RHEL).

88 apt install pkg Packages Install (Ubuntu).

89 rpm -qa | grep Packages Check installed RPM.

90 systemctl status Services Check service status.

91 systemctl start Services Start service.

92 systemctl enable Services Enable at boot.

93 printenv Env Vars List all env variables.

94 export VAR=val Env Vars Set env variable.

95 crontab -e Scheduler Edit cron jobs.

96 crontab -l Scheduler List cron jobs.

97 at 5pm Scheduler One-time scheduled job.

98 useradd user Users Create user.

99 passwd user Users Set/change password.

100 userdel user Users Delete user.

101 usermod -aG g u Users Append to group.


102 groupadd grp Groups Create group.

103 id user Users Show UID/GID/groups.

104 su - user Auth Switch user.

105 sudo cmd Auth Run command as root.

106 visudo Auth Edit sudoers safely.

107 wall "msg" Comm Broadcast to all users.

108 shutdown -h now Admin Immediate shutdown.

109 reboot Admin Restart server.

110 hostnamectl Admin Manage hostname.

111 history Misc Show command history.

112 alias l=ls Misc Create command shortcut.

113 man command Misc Read manual page.

114 tar -czf o dir Archive Compress folder.

115 sosreport Admin Collect system diagnostics.

You might also like