Overview of UNIX Operating System Features
Overview of UNIX Operating System Features
•'˙¸7.s Booting Process (Linux/UNIX-like) directory), $\text{alias}$ (create command shortcuts), $\text{export}$ (set environment
The boot process is a critical sequence that loads the operating system into memory. variables).
1. BIOS/UEFI Initialization: The computer's firmware performs a Power-On Self-Test ($\text{POST}$). External Commands
2. Boot Loader (GRUB): The firmware loads and executes the boot loader from the disk. Definition: Commands that are executable programs stored as separate files on the disk, typically
GRUB presents a menu (if configured) and then loads the Linux kernel into memory. in directories like $\text{/bin}$, $\text{/usr/bin}$, $\text{/sbin}$, etc.
Execution: When an external command is run, the shell must locate the executable file (by
3. Kernel Initialization: The kernel starts, initializes all hardware, and mounts the root file
system ($\text{/}$). searching the directories listed in the $\text{PATH}$ environment variable) and then execute
4. Init System (System Processes): The kernel starts the first system process, historically $\text{init} it, which involves creating a new process.
$, but now commonly Systemd (or $\text{SysVinit}$, $\text{Upstart}$). This system process is Examples: $\text{ls}$ (list directory contents), $\text{grep}$ (search for patterns), $\text{cat}
always assigned Process ID (PID) 1. $ (concatenate files), $\text{mkdir}$ (make directory), $\text{gcc}$ (GNU C compiler).
5. Runlevel/Target Activation: The init system reads configuration files to determine the The $\text{type}$ command can be used to determine if a command is internal or external (e.g.,
desired operating state (e.g., multi-user, networking, GUI). It then starts all necessary $\text{type ls}$ vs. $\text{type cd}$).
system services (daemons) and ultimately presents the user with a login prompt (CLI or
GUI). ⬛.-' Creation of Partitions in OS
● Shutdown Process Partitioning is the act of dividing a physical or logical disk drive into one or more independent sections.
A proper shutdown is essential to ensure all data is written to disk and all processes are terminated cleanly. Each section, or partition, is treated as a separate disk drive by the operating system.
Necessity:
1. Shutdown Command: A user or script issues a command (like $\text{shutdown}$, $\text{halt}$, or
o Multiple OSes: To install multiple operating systems (dual-booting).
$\text{poweroff}$).
o Data Isolation: To separate system files from user data, improving security and simplifying backups.
2. Signaling: The init system (Systemd/init) receives the request and sends a signal (e.g.,
o Performance: Placing frequently accessed data (like $\text{/tmp}$ or $\text{/var}$) on dedicated
$\text{SIGTERM}$) to all running processes (except PID 1) to ask them to terminate gracefully.
3. Unmounting: The system unmounts all file systems to prevent data corruption. partitions can sometimes improve performance and prevents a runaway log file from filling up
4. Kernel Halt: The kernel completes its final tasks and sends a signal to the hardware to halt or the entire system disk.
power off. Common UNIX/Linux Partition Schemes
While basic installations require only $\text{/}$ (root) and $\text{swap}$, complex systems often have
◦O☼ System Processes (An Overview) dedicated partitions for:
A process is an instance of a running program. In UNIX, processes are the fundamental unit of work. $\text{/}$ (Root): The primary partition where the OS and core files reside.
PID 1 (Init System): The very first process started by the kernel. It is the parent of all $\text{/home}$: Stores user accounts, settings, and personal files. Separating this allows the OS
other processes and is responsible for managing the state of the entire system. to be reinstalled without losing user data.
Daemons: Background processes that run continuously to provide services (e.g., web server $\text{/var}$: Stores variable data, such as log files, mail queues, and temporary files created
$\text{httpd}$, mail server $\text{sendmail}$, logging service $\text{syslogd}$). Their names by applications.
traditionally end with the letter $\text{d}$. $\text{/boot}$: Stores the files necessary for the boot process (kernel, boot loader configuration).
Foreground/Background: Swap: Used as an extension of physical RAM.
o Foreground processes interact directly with the user's terminal. Tools like $\text{fdisk}$, $\text{gparted}$, and $\text{parted}$ are used for creating and managing
o Background processes run independently, freeing up the terminal for other work (often started partitions. Once partitions are created, they must be formatted with a file system (e.g., $\text{ext4}$) and
with the $\text{\&}$ symbol). then mounted to a specific directory (a mount point) in the root file system.
The $\text{ps}$ command is used to view currently running processes, and the $\text{kill}$ command is
used to send signals to processes, typically to terminate them. ³⬛– Processes and its Creation Phases
A process is a program in execution. The ability to create new processes efficiently is central to UNIX's
, External and Internal Commands multi-tasking nature. A process is typically identified by its unique Process ID (PID) and has attributes like
UNIX commands are the core interface for interacting with the system. They are categorized based on a
where their executable code resides. $\text{parent PID (PPID)}$, memory space, open file descriptors, and priority.
Process creation in UNIX is a two-step process involving the $\text{fork()}$ and $\text{exec()}$ system
calls, followed by the parent process using $\text{wait()}$ and the child process using $\text{exit()}$.
1. Fork ($\text{fork()}$)
Purpose: To create a new process that is an exact duplicate of the calling process (the parent). Unit-2
Mechanism: The $\text{fork()}$ system call creates a child process. Both processes (parent User Management and the File System: Types of Users, Creating users, Granting rights, User management
and child) continue execution immediately after the $\text{fork()}$ call. commands, File quota and various file systems available, File System(hard links, symbolic links)
Return Value: $\text{fork()}$ returns different values to distinguish the two: Management and Layout, File permissions, Login process, Managing Disk Ouotas, Links
o To the Parent Process: Returns the PID of the child.
o To the Child Process: Returns 0.
o On failure: Returns -1. †ç, Unit-2: User Management and the File System
Result: After a successful $\text{fork()}$, the parent and child share a copy of the parent's This unit covers the fundamental concepts of how UNIX-like operating systems manage user identities,
memory, although they are completely independent processes with separate PIDs. access rights, and the organization of data through its highly structured file system. Understanding these
2. Exec ($\text{exec()}$ Family) concepts is essential for security, system administration, and effective UNIX programming.
Purpose: To replace the current process's memory space and code with a new program.
Mechanism: The $\text{exec()}$ (e.g., $\text{execlp}$, $\text{execv}$) system call loads a ¡†'^ˇˆˇˆ˙’'˙쩣쩢‘'쩟쩞˜ˇ^'`^˜ Types of Users in UNIX
new executable file into the memory space of the calling process. UNIX-like operating systems categorize users into distinct types, each possessing different levels of
Result: If successful, the process (usually the child created by $\text{fork()}$) effectively authority and responsibility. This structure is the cornerstone of UNIX security and multi-user capability.
transforms into the new program. The $\text{PID}$ remains the same, but the program being The three primary categories of users are:
executed is now completely different. The $\text{exec()}$ call never returns to the calling 1. Root User (or Superuser):
program if successful. o Identity: Often referred to by the username $\text{root}$ and always associated with User ID
Combined $\text{fork()}$ and $\text{exec()}$: This is the standard way a shell runs a command. The shell (UID) 0.
($\text{parent}$) $\text{fork()}$s a new process ($\text{child}$). The $\text{child}$ then $\text{exec()}$s o Authority: The $\text{root}$ user possesses absolute, unrestricted power over the entire system.
the command (e.g., $\text{ls}$), and the $\text{parent}$ waits. It can read, write, and execute any file, modify any system configuration, manage all processes,
3. Wait ($\text{wait()}$ Family) and access any peripheral device. It bypasses all standard file permissions checks.
Purpose: To make the parent process pause its execution until one of its child o Role: The $\text{root}$ account is exclusively for system administration tasks, maintenance,
processes terminates. and troubleshooting. Due to the inherent danger of its power, administrators rarely log in
Mechanism: When the parent calls $\text{wait()}$, it blocks. When a child process terminates, the directly as
operating system releases the child's resources and turns it into a zombie process (a temporary $\text{root}$. Instead, they use commands like $\text{su}$ (substitute user) or $\text{sudo}$
state where only the entry in the process table remains). The $\text{wait()}$ call retrieves the (superuser do) from a regular user account to temporarily elevate privileges, minimizing the risk
child's exit status and allows the kernel to completely clean up the child's entry, thus "reaping" the of accidental system damage.
zombie. 2. Regular Users:
Importance: If a parent process terminates without waiting for its children, the children become o Identity: These are the standard accounts created for individuals or specific services. Each
orphan processes. The init system (PID 1) automatically adopts orphaned processes and waits regular user is assigned a unique UID, typically starting from 1000 upwards (on modern Linux
for them, preventing permanent zombies. systems).
4. Exit ($\text{exit()}$ Family) o Authority: Regular users operate under the principle of least privilege. They are restricted to their
Purpose: To cause the current process to terminate. own home directories and specific system resources. They cannot modify system-wide files,
Mechanism: When a process calls $\text{exit()}$ (or $\text{_exit()}$ in C/C++) or simply access files owned by other users without explicit permission, or perform administrative tasks
returns from the $\text{main}$ function, it signals to the kernel that it is finished. unless granted specific permissions (via $\text{sudo}$).
Result: The process's resources (memory, open files) are released, and an exit status (an integer, o Role: Their primary role is to run applications, store personal files, and perform tasks related
typically 0 for success, non-zero for error) is passed back to its parent process via the $\text{wait()} to their function without impacting the security or stability of the core operating system.
$ call. This exit status is crucial for shell scripts to determine the success or failure of a command. 3. System Users:
o Identity: These are non-human accounts created during the operating system installation or when
installing service applications (like web servers or databases). They have UIDs typically below
1000.
o Authority: System users are heavily restricted and do not have login access. Their authority is
strictly limited to running their associated service. For instance, the $\text{daemon}$ user runs
various system daemons, and the $\text{www-data}$ or $\text{apache}$ user runs the web
server.
o Role: They exist to isolate services for security. If a service running under a specific system user
is compromised, the attacker's access is limited only to the files and resources associated with
that low-privilege system user, preventing system-wide compromise.
immediately run the $\text{passwd}$ command to set an initial password and enable the command is used by the administrator to set the specific soft and hard limits for users or groups;
account. and the $\text{repquota}$ command generates a report on the current disk usage and quota
Granting Rights (Group Membership and $\text{sudo}$) limits.
Granting rights involves modifying a user's permissions beyond the default: Various File Systems Available
1. Group Membership: The $\text{usermod}$ command is used to add a user to secondary, or The file system defines how data is stored, retrieved, and organized on a storage device. UNIX supports
supplementary, groups. Group membership dictates access to shared resources. For instance, many file systems, each optimized for different needs.
adding a user to the $\text{staff}$ group grants them access to shared project files that are 1. Ext Family (Extended File System):
group- owned by $\text{staff}$. o $\text{ext2}$: The original second extended file system. Lacks journaling.
o Example: $\text{usermod -aG groupname username}$ o $\text{ext3}$: An improvement on $\text{ext2}$ that added journaling. Journaling is a
2. Elevated Privilege ($\text{sudo}$): To allow a regular user to perform administrator tasks feature where the file system keeps a log (a journal) of changes before they are committed,
temporarily, they must be granted $\text{sudo}$ access. This is achieved by adding the user to which significantly improves recovery speed after an unexpected power loss or system crash.
the o $\text{ext4}$: The current standard and default for most Linux distributions. It introduces
$\text{sudo}$ group (or $\text{wheel}$ group on some distributions) or by explicitly listing their command features like extents (to improve handling of large files), persistent pre-allocation, and much
permissions in the $\text{/etc/sudoers}$ file. When a $\text{sudo}$-enabled user executes a command larger file and volume limits. It is highly robust and backward-compatible.
with $\text{sudo}$, they must authenticate with their own password, and the command runs with 2. XFS: A high-performance journaling file system designed by SGI. It excels with very large file
$\text{root}$ privileges. systems and high concurrency, making it popular for high-end server environments.
User Management Commands 3. Btrfs (B-tree File System): A modern, next-generation file system focused on fault tolerance,
repair, and easy administration. Key features include copy-on-write (CoW) architecture, built-in volume
Command Purpose
management, and the ability to create snapshots (read-only, instant copies of the file system).
$\text{useradd}$ Creates a new user account and associated files. 4. NFS (Network File System): A distributed file system protocol that allows a user to access files
over a computer network in the same way they access local storage.
$\text{usermod}$ Modifies an existing user account (e.g., changes shell, home directory, adds to 5. FAT/NTFS: Supported primarily for interoperability with Microsoft Windows systems.
groups).
▲. File System Management and Layout
$\text{userdel}$ Deletes a user account. Often used with the $\text{-r}$ flag to remove the user's The UNIX file system is characterized by its hierarchical, tree-like structure, which starts from a single
home directory as well. root directory, denoted by $\text{/}$. This unified structure means that all files, directories, and even
devices are organized under the same root, regardless of which physical disk they reside on.
$\text{passwd}$ Sets or changes a user's password. The File System Hierarchy Standard (FHS) defines the specific purpose of key top-level directories:
$\text{/}$ (Root): The top-most directory.
$\text{groupadd}$ Creates a new group. $\text{/bin}$ and $\text{/usr/bin}$: Contain essential binary (executable) commands available
to all users.
$\text{gpasswd}$ Manages a group's members and password (though group passwords are rarely
$\text{/sbin}$ and $\text{/usr/sbin}$: Contain system binaries, usually reserved for the
used).
$\text{root}$ user or system administration.
$\text{id}$ Displays the UID and all associated Group IDs (GIDs) of a user. $\text{/etc}$: Holds system-wide configuration files (e.g., $\text{/etc/passwd}$,
$\text{/etc/fstab}$).
$\text{whoami}$ Displays the effective user ID (the current username). $\text{/home}$: Contains the home directories for regular users.
$\text{/var}$: Stores variable data, such as log files, mail, and temporary application files (data
that changes frequently).
$\text{/usr}$: Contains secondary hierarchy for user data, including most applications, libraries,
and documentation. 1. Terminal/Display Prompt: A process called $\text{getty}$ (or a modern equivalent like
$\text{/proc}$: A virtual file system that provides an interface to the kernel's internal $\text{agetty}$) monitors a terminal device (physical console or virtual terminal) and displays the
data structures (processes, memory, etc.). It exists only in memory. $\text{login:}$ prompt.
$\text{/dev}$: Contains special device files representing physical hardware components 2. Username Input: The user types their username.
(terminals, disk drives, printers). 3. Password Input: $\text{getty}$ executes the $\text{login}$ program, which prompts for
File System Management involves tasks like mounting and unmounting file systems, checking for the password.
consistency ($\text{fsck}$), and resizing partitions. The $\text{mount}$ command is crucial, as it logically 4. Authentication: The $\text{login}$ program uses system libraries (often utilizing Pluggable
attaches a file system located on a device (like a hard drive partition or a CD-ROM) to a specific directory Authentication Modules, or PAM) to verify the password against the stored,
(the mount point) in the existing file hierarchy. cryptographically hashed password found in the $\text{/etc/shadow}$ file.
5. Environment Setup: If authentication succeeds:
)¶뮄 File Permissions o The user's home directory is set as the current working directory.
UNIX security is fundamentally based on file permissions, which control who can access what and how. o The user's environmental variables (like $\text{PATH}$, $\text{HOME}$, $\text{SHELL}$)
Permissions are managed for three distinct categories of users regarding a specific file or directory: are initialized.
o The kernel sets the User ID (UID) and Group IDs (GIDs) for the process to those of the
User Category Description
authenticated user.
Owner (u) The user who created the file or directory. 6. Shell Execution: The $\text{login}$ program executes the user's default shell (as specified in
$\text{/etc/passwd}$, e.g., $\text{/bin/bash}$) which, in turn, reads its startup files (e.g., $\text{.bashrc}$,
Group (g) Members of the primary group associated with the file. $\text{.profile}$) and presents the final command prompt.
Other (o) All other users on the system (the public). 꼏 ³ Links: Hard Links and Symbolic Links
Links are pointers that allow a single file to be accessed via multiple names or paths within the file
The permissions themselves are represented by three distinct rights:
system. UNIX supports two fundamentally different types of links: hard links and symbolic (soft) links.
Permission Abbreviation Numeric Description 1. Hard Links
Value Nature: A hard link is essentially a second directory entry (a second file name) that points to
the exact same inode as the original file. The inode is the data structure that stores all file
Read r 4 Allows viewing the file's contents or listing a directory's metadata (permissions, ownership, location of data blocks).
contents. Behavior: The file's contents and metadata remain in existence as long as at least one hard link
(name) points to the inode. Deleting one hard link only decrements the link count associated
Write w 2 Allows modifying, saving, or deleting the file, or
with the inode. The data is only truly deleted when the link count reaches zero.
creating/deleting files within a directory.
Restrictions: Hard links can only be created for files (not directories) and only within the same
directly modify the current environment (e.g., set variables or change the current directory). JOIN operation in database SQL.
Syntax: There are two common ways to define a function in $\text{Bash}$: Prerequisite: Both input files must be sorted on the join field before the $\text{join}$ command
Bash is executed.
# Standard POSIX format Mechanism: It finds lines in the two files that have the same value in a designated field and
function_name () { outputs a line containing the fields from both matched entries.
# Commands Example: $\text{join -1 2 -2 1 file1 file2}$ (Joins file 1 using field 2, and file 2 using field 1).
# Bash-specific keyword Mechanism: It takes input from $\text{stdin}$ and outputs the result to $\text{stdout}$. It
format function works with two sets of characters: $\text{SET1}$ and $\text{SET2}$.
function_name { o Translation: It replaces characters in the input that match a character in $\text{SET1}$ with
# Commands the character at the corresponding position in $\text{SET2}$.
} Example: $\text{echo "aBcD" | tr a-z A-Z}$ (Converts all lowercase letters to uppercase).
o Deletion: Using the $\text{-d}$ option, it deletes all occurrences of characters specified in
$\text{SET1}$.
Argument Handling: Arguments passed to the function are accessed positionally, similar to Example: $\text{tr -d ' ' < file}$ (Removes all spaces from the file).
script arguments: 5. $\text{uniq}$ Utility (Unique)
o $\text{\$1}$, $\text{\$2}$, ...: Positional arguments passed to the function. Purpose: To filter out or report repeated lines in a file or data stream.
o $\text{\$@}$: All arguments passed to the function. Prerequisite: The input data must be sorted for $\text{uniq}$ to detect duplicate lines correctly,
o $\text{\$#}$: The number of arguments passed to the function. as it only compares adjacent lines. This is why $\text{uniq}$ is almost always preceded by the
Return Value: A function returns its status using the $\text{return}$ command, which must be $\text{sort}$ utility in a pipe.
an integer between 0 and 255. Like any command, 0 indicates success, and non-zero indicates Key Options:
failure. The exit status of the last executed command within the function is captured in the $\ o $\text{-u}$: Prints only the lines that are unique (occur only once).
text{\$?}$ variable. o $\text{-d}$: Prints only the lines that are duplicated (occur two or more times).
o $\text{-c}$: Counts the number of times each line occurred and prepends the count to the line.
꽎 Utility Programs (Filters) Example: $\text{sort [Link] | uniq -c}$ (Sorts the file, then counts the occurrence of each
UNIX programming heavily relies on combining small, specialized utilities (filters) via pipes to perform unique line).
complex data transformations. The following utilities are fundamental for text processing.
1. $\text{cut}$ Utility
Purpose: To extract specific sections (fields, columns, or bytes) from each line of a file or ˙•Q Pattern Matching Utility ($\text{grep}$)
piped input. $\text{grep}$ (Global Regular Expression Print) is arguably the most powerful and widely used utility in
Mechanism: It operates by defining a delimiter (e.g., a comma, a colon, or a space) and UNIX. It is designed to search text data for lines that match a specified pattern and print the matching lines
then selecting the field numbers to output. to standard output.
Key Options: Regular Expressions (Regex)
o $\text{-d}$: Specifies the delimiter character (default is the tab character). $\text{grep}$ uses Regular Expressions (Regex), which are sequences of characters that define a search
o $\text{-f}$: Specifies the field numbers to cut. pattern. Regex allows for complex and flexible pattern matching, such as searching for lines that start with
o $\text{-c}$: Specifies the character positions (columns) to cut. a specific word, end with a number, or contain a sequence of characters that repeat a certain number of
Example: $\text{cut -d: -f1,7 /etc/passwd}$ (Extracts the username (field 1) and the default times.
shell (field 7) from the password file, using the colon as the delimiter). Basic Regex Examples:
2. $\text{paste}$ Utility o $\text{^pattern}$: Matches lines starting with "pattern".
Purpose: To merge corresponding lines from multiple input files or data streams into a single o $\text{pattern\$}$: Matches lines ending with "pattern".
line, usually separated by a tab character. It is the logical inverse of $\text{cut}$. o $\text{^pattern\$}$: Matches lines containing only "pattern".
Mechanism: It reads one line from each input file simultaneously and then concatenates o $\text{.}$: Matches any single character.
them horizontally. o $\text{*}$: Matches zero or more occurrences of the preceding character.
$\text{grep}$ Variants
There are three main versions of the $\text{grep}$ command, differing in the type of regular expression
syntax they support:
□굠_¿ DSE-1: UNIX PROGRAMMING - Logic Programs
Unit 1: Introduction & Processes
1. $\text{grep}$ (Basic $\text{grep}$): Supports Basic Regular Expressions (BRE), where
characters like $\text{+, ?, |}$ need to be escaped with a backslash ($\text{\}$) to be treated as # Program Description Bash Script Code
special operators.
2. $\text{egrep}$ (Extended $\text{grep}$): Supports Extended Regular Expressions (ERE) (same as 1 System Info Script: bash #!/bin/bash echo "--- System Information ---" echo "Operating
$\text{grep -E}$), where $\text{+, ?, |}$ are treated as special operators without needing to be Display system name, System Name: $(uname -s)" echo "Kernel Version: $(uname -r)"
escaped. ERE is generally preferred for modern, complex pattern matching. kernel version, current echo "Current User: $(whoami)" echo "Current Directory: $(pwd)"
3. $\text{fgrep}$ (Fixed $\text{grep}$): Searches for fixed strings only (same as $\text{grep -F}$). It user, and working echo "Current Shell: $SHELL"
does not interpret any characters as regular expression operators, making it much faster for directory.
simple, exact text searches.
Key $\text{grep}$ Options 2 Basic Fork Simulation: bash #!/bin/bash echo "Parent process (PID: $$) is starting." # Start
Script that runs a a simple command in the background (simulating fork) sleep 5 & #
Option Purpose background process and Capture the PID of the last background command LAST_PID=$! echo
reports its PID and the "Child process started in background with PID: $LAST_PID" echo
$\text{-v}$ Inverts the match, printing lines that do not match the pattern.
parent's PID. "Parent is waiting for 2 seconds..." sleep 2 # Check status of the
$\text{-i}$ Ignores case distinctions in both the pattern and the input file. background job (simulating wait) wait $LAST_PID echo "Child
process $LAST_PID has finished."
$\text{-l}$ Lists only the names of the files containing matches, not the matching lines themselves.
3 Check Command Type: bash #!/bin/bash read -p "Enter a command (e.g., ls or cd): " cmd
$\text{-c}$ Prints only a count of the matching lines. Determines if a user- type "$cmd"
supplied command is
$\text{-r}$ Recursively searches for the pattern in all files under the specified directory. external or internal
(built-in).
Example: $\text{grep -iv "error" [Link]}$ (Finds all lines in $\text{[Link]}$ that do not
contain the word "error", ignoring case).
4 Process Status Check: bash #!/bin/bash echo "Processes owned by $(whoami):" ps -u
The power of $\text{grep}$, when combined with pipes and other filters, makes it a cornerstone of
Lists the processes $(whoami)
data analysis and logging review in the UNIX environment.
owned by the current
user.
6 Execute Multiple ```bash #!/bin/bash echo "Counting files and directories in the
External Commands: current folder:" ls -1
Chains $\text{ls}$ and
$\text{wc}$ to count
files.
7 Print Command-Line bash #!/bin/bash echo "The script name is: $0" echo "Total
Arguments: Displays all arguments passed: $#" echo "All arguments: $@"
arguments passed to the
script.
8 Display System Time: bash #!/bin/bash echo "Current Date and Time:" date "+%Y-%m-%d
Uses the $\text{date}$ %H:%M:%S %Z"
command to format the directory." else echo "'$PATH_INPUT' is another type of file or
output. does not exist." fi
9 Disk Space Check: ```bash #!/bin/bash echo "Filesystem Usage Report:" df -h 17 Create Symbolic Link: bash #!/bin/bash TARGET="original_data.txt"
Reports the free disk Creates a symbolic link to a LINK_NAME="data_symlink" # Create dummy target touch
space on the system. target file. "$TARGET" ln -s "$TARGET" "$LINK_NAME" echo "Symbolic link
'$LINK_NAME' created, pointing to '$TARGET'." ls -l
10 Simple File Creation: bash #!/bin/bash FILE_NAME="test_file_$(date +%s).txt" touch "$LINK_NAME"
Creates an empty file and "$FILE_NAME" if [ -f "$FILE_NAME" ]; then echo "Empty file
confirms its creation. '$FILE_NAME' created successfully." else echo "Error creating file." 18 Create Hard Link: Creates a bash #!/bin/bash TARGET="shared_data.txt"
fi hard link to a target file. LINK_NAME="data_hardlink" # Create dummy target echo
"Initial content" > "$TARGET" ln "$TARGET" "$LINK_NAME"
11 Check Exit Status: bash #!/bin/bash # Try to list a non-existent directory ls echo "Hard link '$LINK_NAME' created for '$TARGET'." ls -li
Executes a command and /nonexistent_dir 2>/dev/null ECHO_STATUS=$? echo "Exit status of "$TARGET" "$LINK_NAME" # Display inodes
reports its exit status. the previous command (ls): $ECHO_STATUS" # Try a successful
command ls / 2>/dev/null ECHO_STATUS=$? echo "Exit status of the 19 List System Users: Extracts ```bash #!/bin/bash echo "List of system users:" cut -d: -f1
previous command (successful ls): $ECHO_STATUS" and prints only the /etc/passwd
usernames from
12 Use of $\text{echo}$ bash #!/bin/bash MY_VAR="World" echo "1. Double Quotes: Hello $\text{/etc/passwd}$.
and Quotes: $MY_VAR" echo '2. Single Quotes: Hello $MY_VAR'
Demonstrates the 20 Check User Group bash #!/bin/bash CURRENT_USER=$(whoami) echo "Groups for
difference between Membership: Reports all user $CURRENT_USER:" groups $CURRENT_USER
single and double groups the current user
quotes. belongs to.
21 Check if Root User: Uses the bash #!/bin/bash if [ "$(id -u)" -eq 0 ]; then echo "Running as
Unit 2: User Management and the File System UID to determine if the script the ROOT user (UID 0)." else echo "Running as a REGULAR user
# Program Description Bash Script Code is run by the root user. (UID: $(id -u))." fi
13 Check File Permissions: bash #!/bin/bash read -p "Enter filename: " FILE_PATH if [ -r 22 Automate Directory bash #!/bin/bash PROJECT_ROOT="new_project_$(date
Determines if a user-supplied "$FILE_PATH" ]; then echo "$FILE_PATH is readable." else echo Creation: Creates a specific +%H%M%S)" mkdir -p "$PROJECT_ROOT"/src
file is readable, writable, and "$FILE_PATH is NOT readable." fi if [ -w "$FILE_PATH" ]; then directory structure "$PROJECT_ROOT"/docs echo "Created project structure at:
executable. echo "$FILE_PATH is writable." else echo "$FILE_PATH is NOT ($\text{project/src, $PROJECT_ROOT" ls -R "$PROJECT_ROOT"
writable." fi if [ -x "$FILE_PATH" ]; then echo "$FILE_PATH is project/docs}$).
executable." else echo "$FILE_PATH is NOT executable." fi
23 Check File Existence bash #!/bin/bash FILE_NAME="check_me.log" if [ -e
14 Change File Permissions bash #!/bin/bash read -p "Enter filename to change to 755: " (Conditional): Checks if a file "$FILE_NAME" ]; then echo "$FILE_NAME exists. Displaying first
(Numeric): Changes FILE_PATH if [ -e "$FILE_PATH" ]; then chmod 755 "$FILE_PATH" exists before attempting to line:" head -n 1 "$FILE_NAME" else echo "$FILE_NAME does not
permissions of a specified echo "Permissions of $FILE_PATH set to 755 (rwxr-xr-x)." else read it. exist. Skipping read operation." fi
file to 755. echo "File not found." fi
24 Check Home Directory Size: bash #!/bin/bash HOME_DIR="$HOME" echo "Calculating disk
15 List File Owner and Group: ```bash #!/bin/bash read -p "Enter filename: " FILE_PATH if [ -e Calculates the total disk usage for $HOME_DIR..." # -s: summarize, -h: human-readable
Displays the owner and "$FILE_PATH" ]; then echo "Owner and Group for $FILE_PATH:" usage of the current user's du -sh "$HOME_DIR"
group of a file using $\text{ls ls -ld "$FILE_PATH" home directory.
-ld}$.
16 Identify File Type: Checks if bash #!/bin/bash read -p "Enter path: " PATH_INPUT if [ -f
the input is a regular file or a "$PATH_INPUT" ]; then echo "'$PATH_INPUT' is a regular file."
directory. elif [ -d "$PATH_INPUT" ]; then echo "'$PATH_INPUT' is a
Unit 3: Shell Introduction and Shell Scripting 34 Check String Equality: bash #!/bin/bash STR1="UNIX" STR2="unix" if [ "$STR1" ==
# Program Description Bash Script Code Compares two strings for "$STR2" ]; then echo "Strings are equal." else echo "Strings are
equality. NOT equal (case-sensitive)." fi
25 Simple Arithmetic bash #!/bin/bash # Check for exactly two arguments if [ $# -ne 2 ];
Calculation: Takes two then echo "Usage: $0 <num1> <num2>" exit 1 fi num1=$1 35 Basic Input/Output bash #!/bin/bash OUTPUT_FILE="log_data.txt" echo "Starting log
numbers as arguments and num2=$2 # Use arithmetic expansion (( )) SUM=$(( num1 + num2 Redirection: Redirects $(date)" > "$OUTPUT_FILE" # Overwrite echo "First entry" >>
prints their sum and )) PRODUCT=$(( num1 * num2 )) echo "Sum of $num1 and $num2 output to a file and "$OUTPUT_FILE" # Append echo "Second entry" >>
product. is: $SUM" echo "Product of $num1 and $num2 is: $PRODUCT" appends. "$OUTPUT_FILE" echo "Log written to $OUTPUT_FILE." cat
"$OUTPUT_FILE"
26 Basic Function Definition: bash #!/bin/bash # Function definition greet_user () { local
Defines and calls a name=$1 echo "Hello, $name! Welcome to the Bash Scripting 36 Using $\text{until}$ bash #!/bin/bash count=1 until [ $count -gt 5 ]; do echo "Count:
function to greet a user. environment." } # Function call with argument greet_user Loop: Waits until a $count" count=$((count + 1)) sleep 1 done echo "Loop finished."
"Student" certain count is reached.
27 File Processing with bash #!/bin/bash # Create a temporary file for demonstration
$\text{while}$ Loop: echo -e "Line 1\nLine 2\nLine 3" > temp_input.txt count=1 while Unit 4: Control Structures and Utilities
Reads a file line-by-line IFS= read -r line; do echo "Processing line $count: $line" # Program Description Bash Script Code
using a $\text{while}$ count=$((count + 1)) done < temp_input.txt rm temp_input.txt
loop. 37 Use of $\text{grep}$: Searches bash #!/bin/bash FILE="[Link]" KEYWORD="error" #
a file for all lines containing a Create dummy file echo -e "Error line 1\nSuccess
28 C-Style $\text{for}$ Loop: bash #!/bin/bash echo "Odd numbers from 1 to 9:" for (( i=1; i<=9; specific keyword, ignoring case. entry\nwarning\nAnother error" > "$FILE" echo "Lines
Prints odd numbers from 1 i+=2 )); do echo $i done containing '$KEYWORD' (case insensitive):" grep -i
to 9. "$KEYWORD" "$FILE" rm "$FILE"
29 List Iteration $\text{for}$ bash #!/bin/bash NAMES="Alice Bob Charlie David" echo 38 Use of $\text{cut}$ and ```bash #!/bin/bash echo "First 5 usernames in uppercase:" #
Loop: Iterates over a list of "Iterating over names:" for name in $NAMES; do echo "Next name $\text{tr}$: Extracts the 1. Cut field 1 (username) using ':' delimiter cut -d: -f1
names and prints them. is: $name" done usernames from /etc/passwd
$\text{/etc/passwd}$ and
30 Simple $\text{if-else}$ bash #!/bin/bash read -p "Enter an integer: " number # Use -gt converts them to uppercase.
Statement: Checks if a (greater than) with double parentheses if (( number > 0 )); then
number is positive or echo "$number is positive." elif (( number < 0 )); then echo 39 $\text{sort}$ and $\text{uniq}$ ```bash #!/bin/bash INPUT_TEXT="apple banana apple
negative. "$number is negative." else echo "The number is zero." fi with $\text{-c}$: Finds the orange banana apple" echo "Word Frequencies:" # 1.
frequency of each unique word Replace spaces/newlines with newline, convert to lowercase
31 $\text{case}$ Statement bash #!/bin/bash echo "Select an option:" echo "1) Show Date" in a given string. tr ' ' '\n' <<< "$INPUT_TEXT"
for Menu: Implements a echo "2) Show Calendar" read -p "Your choice (1 or 2): " choice
simple menu using the case $choice in 1) date ;; 2) cal ;; *) echo "Invalid option selected." 40 Use of $\text{cut}$ and bash #!/bin/bash # Create two column files echo -e
$\text{case}$ structure. ;; esac $\text{paste}$: Creates two "A\nB\nC" > [Link] echo -e "1\n2\n3" > [Link] echo
columns of data and pastes "Pasting columns:" # Paste them together with the default
32 Use of $\text{export}$: bash #!/bin/bash MY_GREETING="Hello from Parent!" export them together. TAB delimiter paste [Link] [Link] rm [Link] [Link]
Defines a variable in the MY_GREETING echo "Parent defined and exported
script and exports it to a MY_GREETING." # Run a subshell to check the variable bash -c 41 Function with Positional ```bash #!/bin/bash calculate_area () { local length=$1 local
child process. 'echo "Child process received: $MY_GREETING"' Arguments: Calculates the area width=$2 # Check if arguments are numeric if ! [[ "$length"
of a rectangle using a function. =~ ^[0-9]+$ ]]
33 Check String Length: Takes bash #!/bin/bash read -p "Enter a string: " input_string # Use -z
a string input and checks if (zero length) operator if [ -z "$input_string" ]; then echo "The 42 $\text{grep -v}$ (Inverse bash #!/bin/bash FILE="[Link]" # Create dummy file
it's empty. string is empty." else echo "The string length is not zero." fi Match): Prints all lines from a echo -e "user=admin\n# This is a
file except the ones containing comment\npath=/var/www\n# Another comment" > "$FILE"
comments ($\text{#}$). echo "Configuration lines (excluding comments):" # -v: Invert
match grep -v '^#' "$FILE" rm "$FILE"
LONG QUESTIONS
43 String Case Conversion ```bash #!/bin/bash read -p "Enter mixed-case text: "
($\text{tr}$): Converts script mixed_case_input lower_case_output=$(echo ### Unit-1: Introduction to Unix Operating Systems (First 5 Questions)
input to lowercase. "$mixed_case_input" 1. **Analyze the evolution of UNIX operating systems from its origins to modern
distributions, emphasizing key milestones and their impact on computing.**
44 $\text{if}$ with Command bash #!/bin/bash FILE="check_lines.txt" # Create dummy file - UNIX originated in 1969 at Bell Labs by Ken Thompson and Dennis Ritchie, initially as a
Substitution: Uses the output of with a few lines echo -e "a\nb\nc\nd\n" > "$FILE" multitasking system for the PDP-7, evolving from Multics to a simpler, portable design that
a command ($\text{wc}$) in a LINE_COUNT=$(wc -l < "$FILE") if [ "$LINE_COUNT" -gt 3 ]; influenced open-source movements.
conditional check. then echo "The file has $LINE_COUNT lines, which is more - A major milestone was the 1973 rewrite in C, enabling portability across hardware, unlike earlier
than 3." else echo "The file has $LINE_COUNT lines, 3 or assembly-based OSes, and leading to the release of BSD in 1977, which introduced networking
less." fi rm "$FILE" features.
- The 1980s saw commercial UNIX variants like System V from AT&T and SunOS from Sun
45 Parameter Validation with bash #!/bin/bash EXPECTED_ARGS=3 if [ $# -lt Microsystems, standardizing APIs and fostering enterprise adoption for servers.
$\text{if-else}$: Checks if the $EXPECTED_ARGS ]; then echo "Error: Not enough - Linux, created by Linus Torvalds in 1991 as a free UNIX-like kernel, democratized UNIX, integrating
correct number of arguments is arguments supplied." echo "Usage: $0 <arg1> <arg2> GNU tools to form distributions like Ubuntu, emphasizing community-driven development.
supplied. <arg3>" exit 2 else echo "Arguments successfully validated." - Modern distributions incorporate systemd for init management, enhancing boot efficiency, and
fi support for containers like Docker, reflecting UNIX's adaptability to cloud computing.
- Differences from other OSes: UNIX's text-based philosophy contrasts with Windows' GUI
46 $\text{until}$ Loop with bash #!/bin/bash TARGET_FILE="[Link]" echo "Waiting
focus, promoting scripting for automation in data centers.
$\text{sleep}$: Loops until a for file: $TARGET_FILE to appear..." until [ -f "$TARGET_FILE"
- Features like modularity allow custom kernels, unlike macOS's fixed Darwin base, supporting
specific file appears in the ]; do echo "File not found yet, sleeping 3 seconds..." sleep 3
embedded systems.
current directory. done echo "$TARGET_FILE is now present. Continuing
- Installation evolved from floppy disks to ISO images, with tools like Anaconda simplifying partitioning.
script." # Cleanup rm "$TARGET_FILE"
- Booting now uses UEFI for faster hardware detection, loading GRUB to initialize the kernel and
mount file systems.
47 Combine $\text{grep}$ and ```bash #!/bin/bash echo "PIDs of your 'bash' processes:" # 1.
- Shutdown processes include graceful termination of services via systemctl, preventing data loss
$\text{cut}$: Extracts the PIDs Find all processes for the user ps -u $(whoami)
unlike older abrupt halts.
(Process IDs) of the
- System processes like cron daemons automate tasks, building on early UNIX designs.
$\text{bash}$ processes run by
- External commands expanded with package managers like apt, while internal ones remain core to shells.
the current user.
- Partition creation uses LVM for dynamic resizing, improving on static schemes.
48 Calculate Factorial using bash #!/bin/bash read -p "Enter a small integer (1-10): " - Process creation phases—fork for cloning, exec for loading binaries, wait for synchronization, and exit
$\text{for}$ Loop: Calculates NUM if [ $NUM -lt 1 ]; then echo "Factorial is 1." exit 0 fi for cleanup—remain fundamental, enabling robust multi-tasking.
the factorial of an input number. factorial=1 for (( i=1; i<=NUM; i++ )); do factorial=$(( factorial - Overall, UNIX's evolution underscores its role in shaping open-source software, with milestones
* i )) done echo "Factorial of $NUM is: $factorial" like POSIX standards ensuring compatibility across platforms. (Word count: 412)
2. **Compare UNIX's architecture with that of a monolithic kernel OS like Windows NT,
This table provides 48 unique, fundamental logical programs covering the core objectives of all four units. highlighting advantages in stability and modularity.**
The programs are structured for clarity and are fully compliant with standard Bash scripting practices. - UNIX employs a monolithic kernel with modular extensions, where core functions like scheduling
and I/O are integrated, allowing direct hardware access for performance, unlike Windows NT's hybrid
kernel that separates microkernel elements for fault isolation.
- Advantages in stability: UNIX's design minimizes context switches, reducing crashes in multi-
user environments, as seen in server uptime records for Linux distributions.
- Modularity shines in loadable kernel modules (LKMs), enabling dynamic addition of drivers
without reboots, contrasting Windows' need for DLLs and restarts.
- Features like virtual file systems (VFS) abstract storage, supporting diverse file systems seamlessly.
- Installation involves kernel compilation for optimization, differing from Windows' pre-built images.
- Booting loads modules via initramfs, ensuring hardware compatibility.
- Shutdown unloads modules safely, maintaining integrity.
- System processes leverage kernel APIs for efficiency.
- External commands interface via system calls, while internal ones are shell-integrated.
- Partition creation supports RAID for redundancy, enhancing reliability.
- Process phases like fork create lightweight threads, outperforming Windows' heavier processes. - Shutdown uses them for cleanup.
- This architecture fosters UNIX's dominance in high-availability systems, with modularity - System processes invoke external ones.
allowing customization for specific workloads. (Word count: 398) - Partition creation ensures external binaries are accessible.
- Process phases handle command execution.
3. **Detail the installation process of a UNIX distribution like Fedora, including partitioning - This distinction enhances UNIX's usability. (Word count: 372)
strategies and post-installation configurations.**
- Installation starts with downloading the ISO and creating a bootable USB using tools like Rufus, ### Unit-1: Introduction to Unix Operating Systems (Next 5 Questions)
then booting into the live environment for testing. 6. **Describe the booting sequence in UNIX, including the roles of BIOS, bootloader, and
- Partitioning uses Anaconda installer, recommending Btrfs for snapshots or ext4 for stability, allocating kernel initialization.**
/boot (1GB), swap (RAM size), / (20GB), and /home (remaining). - Booting begins with BIOS/UEFI performing POST to check hardware, then loading the bootloader
- Strategies include LVM for flexible resizing and encryption with LUKS for security. from MBR or EFI partition.
- Post-installation involves updating packages via dnf, configuring network with nmcli, and setting up - The bootloader, like GRUB, presents a menu for kernel selection and passes parameters.
users with useradd. - Kernel initialization mounts the initramfs, detects devices, and starts systemd as PID 1.
- Unlike Windows, UNIX installations are scriptable for automation. - It sets up virtual consoles and mounts file systems.
- Booting configures GRUB for multi-OS support. - Differences from Windows: UNIX's sequence is more configurable.
- Shutdown ensures SELinux policies are applied. - Shutdown reverses, syncing disks.
- System processes like firewalld start automatically. - System processes launch post-kernel.
- External commands like vim are installed via repositories. - External commands are available after mount.
- Internal commands handle basic setup. - Internal commands aid in boot scripts.
- Process creation initializes daemons. - Partitioning affects mount order.
- This process emphasizes customization, aligning with UNIX's philosophy. (Word count: 386) - Process creation starts with init.
- This sequence ensures a stable environment. (Word count: 374)
4. **Explain the role of system processes in UNIX, focusing on daemons and their interaction with
user processes during boot and runtime.** 7. **Discuss the shutdown process in UNIX and measures to prevent data loss.**
- System processes are kernel-managed entities that run in the background, with daemons like - Shutdown is initiated by halt or poweroff, signaling all processes to terminate via SIGTERM, then
httpd providing web services without user interaction. SIGKILL if needed.
- During boot, systemd (or init) spawns daemons based on unit files, ensuring dependencies - Measures include syncing file systems with sync, unmounting partitions, and logging events.
like networking precede user logins. - Graceful shutdown avoids corruption, unlike forced reboots.
- Runtime interaction: Daemons communicate via signals or sockets, allowing user processes to - System processes stop in reverse order.
request services, such as cron scheduling tasks. - External commands like umount are used.
- They consume minimal resources, with priorities set via nice values. - Internal commands handle signals.
- Shutdown signals daemons to terminate, logging activities. - Partition integrity is checked.
- External commands query daemons with ps or top. - Process exit is monitored.
- Internal commands like kill manage them. - This process highlights UNIX's robustness. (Word count: 376)
- Partitioning dedicates space for daemon logs in /var.
- Process creation via fork allows daemons to spawn workers. 8. **Explain process creation phases in UNIX, with a focus on fork-exec-wait-exit and their use in
- This setup ensures UNIX's reliability in server environments. (Word count: 378) multi- tasking.**
- Fork duplicates the parent process, creating a child with shared memory for efficiency.
5. **Differentiate between external and internal commands in UNIX, providing examples and - Exec overlays the child with a new program image, like running a script.
discussing their impact on shell efficiency.** - Wait pauses the parent until the child exits, ensuring synchronization.
- Internal commands are built-in to the shell, such as alias for shortcuts or history for command - Exit cleans up resources, returning status.
recall, executed without forking new processes, boosting speed in interactive sessions. - In multi-tasking, this enables concurrent execution.
- External commands reside in file system paths like /usr/bin, e.g., ls or grep, requiring exec to - Booting uses fork for daemons.
load, offering extensibility but with overhead. - Shutdown waits for exits.
- Impact on efficiency: Internal commands reduce latency for frequent operations, while external - System processes rely on these.
ones allow updates without shell recompilation. - External commands are exec'd.
- In scripting, mixing both optimizes performance. - Internal commands integrate.
- Booting loads internal commands early. - Partitioning supports process data.
- Essential for UNIX's design. (Word count: 378)
13. **Discuss the significance of system calls in UNIX architecture.**
9. **Compare UNIX's features with those of real-time OSes, emphasizing architecture differences.** - System calls bridge user and kernel.
- UNIX's general-purpose kernel prioritizes throughput over determinism, unlike RTOSes like VxWorks - Examples: open, read.
with preemptive scheduling for low latency. - Secure operations.
- Features like journaling file systems ensure data integrity, but RTOSes focus on interrupts. - Used in processes.
- Architecture: UNIX's monolithic core vs. RTOS microkernels. - Booting invokes.
- Installation is flexible in UNIX. - Shutdown signals.
- Booting is standard. - Commands rely.
- Shutdown is safe. - Partitions accessed.
- System processes differ. - Core to UNIX. (Word count: 388)
- Commands vary.
- Partitions are similar. ### Unit-2: User Management and the File System (First 5 Questions)
- Processes are adaptable. 1. **Explain the types of users in UNIX and their roles in maintaining system security and
- UNIX suits broad applications. (Word count: 380) resource isolation.**
- In UNIX, users are categorized into root (superuser with UID 0, full system access for
10. **How do external and internal commands integrate with system processes in UNIX?** administration), regular users (standard accounts with limited privileges for daily tasks), and system
- Internal commands manipulate shell state, aiding process management. users (low-privilege accounts for services like daemons, e.g., www-data for web servers).
- External commands call system processes via exec. - Roles in security: Root enforces least privilege by default, while regular users prevent accidental
- Integration allows scripting of daemons. system damage; system users isolate services to avoid privilege escalation.
- Booting loads both. - Resource isolation: Each user has a home directory (/home/username), with permissions
- Shutdown uses them. restricting access, ensuring multi-user environments like servers remain secure.
- Partitions store commands. - Creating users involves assigning unique UIDs/GIDs, preventing conflicts.
- Process phases execute them. - Granting rights uses sudo for temporary elevation, unlike permanent root access.
- Enhances functionality. (Word count: 382) - User management commands like useradd handle creation, with passwd for authentication.
- File quotas limit disk usage per user, preventing resource hogging.
### Unit-1: Introduction to Unix Operating Systems (Next 3 Questions) - Various file systems like ext4 support user-specific quotas.
11. **Detail partition creation in UNIX, including tools and considerations for multi-user setups.** - File system layout places user data in /home, with /etc/passwd storing user info.
- Tools like fdisk create partitions, with gparted for GUI. - File permissions (rwx) control access, with chmod setting them.
- Considerations: Separate /home for users, swap for memory. - Login process authenticates via PAM, checking credentials.
- Supports quotas. - Managing disk quotas uses edquota for soft/hard limits.
- Booting mounts them. - Links: Hard links share inodes for efficiency, symbolic links reference paths securely.
- Shutdown unmounts. - Overall, user types promote a hierarchical security model, crucial for UNIX's multi-user design.
- System processes use. (Word count: 412)
- Commands access.
- Process data stored. 2. **Describe the process of creating users in UNIX, including steps for granting rights and
- Ensures isolation. (Word count: 384) integrating with file systems.**
- User creation starts with the useradd command, specifying options like -m for home directory
12. **Explain UNIX's multi-user capabilities through architecture and processes.** creation and -s for shell assignment, e.g., useradd -m -s /bin/bash newuser.
- Kernel enforces UIDs for isolation. - Granting rights involves adding to groups with usermod -aG groupname user, or using sudoers file
- Processes run per user. for sudo privileges, ensuring controlled access.
- Permissions control. - Integration with file systems: Home directories are created in /home, with permissions set via
- Login authenticates. umask, and quotas applied using setquota.
- Booting initializes. - Post-creation, passwd sets passwords, stored hashed in /etc/shadow.
- Shutdown secures. - Types of users: Regular users get standard rights, while system users (e.g., via useradd -r) have no login.
- Partitions separate. - User management commands automate this, with id showing user details.
- Commands enforce. - File quotas prevent overuse, configured per file system.
- Robust for servers. (Word count: 386) - Various file systems like XFS handle large user bases efficiently.
- File system layout includes /etc/group for group memberships.
- File permissions are inherited from /etc/skel templates. 5. **Compare various file systems available in UNIX, such as ext4, XFS, and ZFS, focusing on
- Login process verifies rights via /etc/passwd. user management features.**
- Managing disk quotas involves quotaon to enable. - ext4: Default in many Linux distros, supports journaling for recovery, quotas, and ACLs for fine-
- Links can be used for shared user resources. grained user permissions.
- This process ensures secure, organized user environments in UNIX. (Word count: 398) - XFS: High-performance for large files, with dynamic inode allocation and project quotas for user groups.
- ZFS: Advanced with snapshots, compression, and built-in quotas, ideal for storage pools and
3. **Discuss user management commands in UNIX, with examples and their impact on user isolation.
system administration.** - User management: All support UIDs/GIDs, but ZFS excels in delegation.
- Key commands include useradd for creation (e.g., useradd -u 1001 -g users john), usermod for - Types of users: File systems enforce per-user access.
modification (e.g., usermod -l jane john to rename), and userdel for deletion (e.g., userdel -r john - Creating users: Home dirs on any FS.
to remove home). - Granting rights: Permissions vary by FS.
- passwd manages passwords (e.g., passwd john), while su switches users and sudo elevates - User management commands: fsck checks integrity.
privileges temporarily. - File quotas: Native in all.
- Impact: These commands streamline administration, reducing errors in multi-user setups, unlike - File system layout: Hierarchical in all.
manual edits to /etc/passwd. - File permissions: POSIX in ext4/XFS, extended in ZFS.
- Types of users: Commands distinguish root from regular. - Login process: FS mounts on login.
- Granting rights: sudoers integrates with commands. - Managing disk quotas: FS-specific tools.
- File quotas: Commands like quota report usage. - Links: Supported universally.
- File systems: Commands mount user-specific volumes. - Choice depends on needs, with ZFS for modern scalability. (Word count: 372)
- File system layout: Commands like chown adjust ownership.
- File permissions: chmod is a core command. ### Unit-2: User Management and the File System (Next 5 Questions)
- Login process: Commands like last show history. 6. **Describe the file system layout in UNIX, including how it supports user management and links.**
- Managing disk quotas: edquota sets limits. - Layout starts with / root, with /home for user directories, /etc for configs, /var for logs, and /usr
- Links: ln creates hard/symbolic links for users. for binaries.
- Overall, these commands enhance efficiency and security in UNIX administration. (Word count: 386) - Supports user management: /etc/passwd and /etc/group store user info, with permissions isolating data.
- Links: Hard links share inodes (e.g., ln file1 file2), symbolic links reference paths (e.g., ln -s
4. **Explain file quotas in UNIX, including how they manage disk usage across different file systems.** /path/to/file link).
- File quotas limit disk space and inodes per user or group, using soft limits (warnings) and hard - Types of users: Layout separates root from users.
limits (blocks), enforced by the kernel. - Creating users: Home creation in /home.
- Management: edquota edits quotas (e.g., edquota username), quotacheck scans usage, and - Granting rights: Permissions on dirs.
repquota reports. - User management commands: chown adjusts ownership.
- Across file systems: Quotas are set per mount point, e.g., ext4 supports them natively, while ZFS - File quotas: Applied to /home.
has built-in quota features. - Various file systems: Layout abstracts via VFS.
- Types of users: Quotas apply to regular users to prevent abuse. - File permissions: rwx on dirs.
- Creating users: Quotas assigned during setup. - Login process: Mounts layout.
- Granting rights: Admins manage quotas. - Managing disk quotas: Per partition.
- User management commands: quota displays current usage. - Links enhance sharing without duplication.
- Various file systems: Btrfs offers subvolume quotas. - This layout ensures organized, secure access. (Word count: 374)
- File system layout: Quotas protect /home.
- File permissions: Quotas respect ownership. 7. **Explain file permissions in UNIX and their role in user management and security.**
- Login process: Quotas load on login. - Permissions are r (read), w (write), x (execute) for owner, group, others, set with chmod (e.g.,
- Managing disk quotas: Tools like quotaon enable. chmod 755 file for rwxr-xr-x).
- Links: Quota counts link usage. - Role: Control access, e.g., 700 for private user files, preventing unauthorized reads.
- This ensures fair resource allocation in multi-user UNIX systems. (Word count: 378) - User management: chown changes owner, chgrp group.
- Types of users: Permissions differentiate root.
- Creating users: umask sets defaults.
- Granting rights: sudo overrides.
- User management commands: ls -l shows permissions.
- File quotas: Permissions limit quota edits. - User management commands: ls -l shows types.
- File systems: Permissions enforced at FS level. - File quotas: Links affect counts.
- File system layout: Permissions on /home. - File systems: Supported in all.
- Login process: Checks permissions. - File system layout: Links in /home.
- Managing disk quotas: Permissions on quota files. - File permissions: Inherited.
- Links: Permissions apply to targets. - Login process: Access links.
- Essential for UNIX security. (Word count: 376) - Managing disk quotas: Links counted.
- Enhances file management. (Word count: 382)
8. **Discuss the login process in UNIX, integrating user management and file system access.**
- Login starts with getty spawning login prompt, authenticating via PAM against /etc/passwd/shadow. ### Unit-2: User Management and the File System (Next 3 Questions)
- Integration: Successful login sets UID/GID, mounts home, and applies quotas. 11. **Integrate user management with file permissions for secure multi-user operations.**
- User management: Commands like who show logins. - User management assigns UIDs/GIDs, while permissions (chmod) restrict access.
- Types of users: Root logs in directly. - Integration: Groups allow shared permissions, e.g., chmod 770 for group write.
- Creating users: Login enables access. - Types of users: Permissions isolate.
- Granting rights: Login checks sudo. - Creating users: Set permissions.
- File quotas: Loaded on login. - Granting rights: sudo for overrides.
- File systems: Mounted securely. - User management commands: chown.
- File system layout: Home accessed. - File quotas: Permissions protect.
- File permissions: Verified. - File systems: Enforce.
- Managing disk quotas: Enforced. - File system layout: Permissions on dirs.
- Links: Available post-login. - Login process: Verifies.
- Ensures authenticated, controlled access. (Word count: 378) - Managing disk quotas: Permissions limit.
- Links: Permissions apply.
9. **How is managing disk quotas implemented in UNIX, with tools and considerations for multi- - Ensures security. (Word count: 384)
user environments?**
- Implementation uses quota tools: quotacheck for scanning, edquota for editing, quotaon for enabling. 12. **Discuss the role of file system layout in supporting user quotas and links.**
- Considerations: Set soft limits for warnings, hard for blocks; per user/group in multi-user setups. - Layout organizes /home for users, /var for quotas. - Supports quotas: Per-dir limits.
- Types of users: Quotas for regulars. - Links: Placed in user dirs. - Types of users: Layout separates.
- Creating users: Assign quotas. - Creating users: Home layout. - Granting rights: Dir permissions.
- Granting rights: Admins set. - User management commands: mkdir. - File quotas: Layout enables.
- User management commands: quota reports. - File systems: Abstract layout. - File permissions: On layout. - Login process: Mounts layout.
- File quotas: Core feature. - Managing disk quotas: Layout stores.
- File systems: Support varies. - Links integrate.
- File system layout: Quotas on /home. - Optimizes management. (Word count: 386)
- File permissions: Limit changes.
- Login process: Applies quotas. 13. **How do various file systems handle user permissions and quotas in UNIX?**
- Links: Counted in usage. - ext4: POSIX permissions, quota via quotactl.
- Prevents resource exhaustion. (Word count: 380) - XFS: Extended attributes, project quotas.
- ZFS: ACLs, dataset quotas.
10. **Explain hard links and symbolic links in UNIX file systems, with examples and user - Handle permissions: Kernel-enforced.
management implications.** - Quotas: FS-specific tools.
- Hard links: Direct inode references (e.g., ln original hardlink), sharing data; deleting original keeps - Types of users: Supported.
data if links exist. - Creating users: FS agnostic.
- Symbolic links: Path pointers (e.g., ln -s /path/to/original symlink), break if target moves. - Granting rights: Permissions set.
- Implications: Hard links save space for users, symbolic for flexibility; permissions apply to targets. - User management commands: FS tools. - File quotas: Core.
- Types of users: Links for sharing. - File system layout: Permissions apply. - Login process: FS mounts.
- Creating users: Links in homes. - Managing disk quotas: Enabled.
- Granting rights: Permissions on links. - Links: Handled. - Flexible for needs. (Word count: 388)
### Unit-3: Shell Introduction and Shell Scripting (First 5 Questions) - Pipes and filters: Scripts use | and grep.
1. **Explain the concept of shells in UNIX, including various types of shells and their features - Ensures automation in UNIX. (Word count: 386)
for scripting.**
- Shells in UNIX are command interpreters that provide a user interface between the user and the 4. **Explain shell variables in UNIX, differentiating between user-defined and system variables
kernel, executing commands and scripts, with the default being Bash in most Linux distributions. with examples.**
- Types include Bourne Shell (sh, basic and portable), C Shell (csh, C-like syntax for programming), Korn - Shell variables store data, user-defined like MYVAR="value" (local to script), system like PATH (global,
Shell (ksh, combines sh and csh features), and Bash (Bourne Again Shell, most popular with /bin:/usr/bin).
enhancements like command history and tab completion). - Examples: User-defined for counters, system for environment.
- Features for scripting: Bash supports variables, loops, conditionals, and functions, making it ideal - Shells: Bash handles both.
for automation, unlike simpler shells. - Various editors: Edit variables in scripts.
- Various editors: Vi is built-in for editing scripts, with modes for input. - Different modes in vi: Modify variables.
- Different modes in vi: Command mode for navigation, insert mode for typing, and ex mode - Shell scripts: Use variables for logic.
for commands. - Writing and executing: Variables persist in sessions.
- Shell scripts: Text files with commands, executed via ./[Link] or bash [Link]. - System calls: Variables pass data.
- Writing and executing: Use editors like vi to write, then chmod +x for execution. - Using system calls: Via scripts.
- Shell variables: User-defined like MYVAR=value, system like PATH for directories. - Pipes and filters: Variables in pipelines.
- System calls: Invoked via scripts, e.g., fork() for processes. - Crucial for scripting flexibility. (Word count: 378)
- Using system calls: Through C programs or shell wrappers.
- Pipes and filters: | connects commands, filters like grep process output. 5. **Discuss system calls in UNIX and how they are used in shell scripting.**
- This versatility makes shells central to UNIX scripting. (Word count: 412) - System calls are kernel interfaces, e.g., open() for files, fork() for processes.
- In scripting: Invoked via commands or C programs called from scripts.
2. **Discuss various editors present in UNIX, with a focus on vi editor and its different modes - Shells: Provide wrappers.
of operation.** - Various editors: Scripts edit call-related code.
- UNIX editors include vi (visual editor, modal and efficient), emacs (extensible with Lisp), nano (simple - Different modes in vi: For scripting.
for beginners), and vim (vi improved with syntax highlighting). - Shell scripts: Use exec for calls.
- Vi editor: Launched with vi filename, operates in modes: command mode (default, for navigation - Writing and executing: Calls in scripts.
with h/j/k/l), insert mode (i for typing), and ex mode (: for commands like :wq to save and quit). - Shell variables: Pass to calls.
- Different modes: Visual mode (v for selection), replace mode (R for overwriting). - Using system calls: Directly in scripts.
- Shells integrate editors, e.g., Bash uses vi for editing commands. - Pipes and filters: Calls handle I/O.
- Various types of shells: Some like csh have built-in editors. - Enable low-level operations. (Word count: 372)
- Shell scripts: Edited in vi for scripting.
- Writing and executing: Vi aids in script creation. ### Unit-3: Shell Introduction and Shell Scripting (Next 5 Questions)
- Shell variables: Edited in scripts. 6. **How are pipes and filters used in UNIX shell scripting for data processing?**
- System calls: Scripts using vi may call editors. - Pipes (|) connect commands, e.g., ls | grep txt filters output.
- Using system calls: Vi uses system calls for file I/O. - Filters like sort, uniq process data.
- Pipes and filters: Vi can pipe output. - In scripting: Automate pipelines.
- Vi's modes enhance productivity in UNIX environments. (Word count: 398) - Shells: Bash supports.
- Various editors: Write scripts.
3. **Describe the process of writing and executing shell scripts in UNIX, including examples.** - Different modes in vi: Edit.
- Writing: Create a file with #!/bin/bash shebang, add commands like echo "Hello", save as [Link]. - Shell scripts: Use pipes.
- Executing: chmod +x [Link], then ./[Link] or bash [Link]. - Writing and executing: Run piped commands.
- Example: A script to list files: #!/bin/bash; ls -l. - Shell variables: In filters.
- Shells: Bash is common for scripts. - System calls: Underlying pipes.
- Various editors: Vi for writing. - Using system calls: For I/O.
- Different modes in vi: Use insert mode for typing. - Essential for efficiency. (Word count: 374)
- Shell variables: Define in scripts, e.g., NAME="User".
- System calls: Scripts can invoke via exec. 7. **Compare different types of shells in UNIX, highlighting their scripting capabilities.**
- Using system calls: For process management. - Sh: Basic, portable.
- Csh: Programming features. - System calls: Variables in.
- Ksh: Advanced. - Using system calls: Via vars.
- Bash: Most versatile. - Pipes and filters: Vars in.
- Capabilities: Bash excels in scripting. - Improves automation. (Word count: 382)
- Various editors: Compatible.
- Different modes in vi: For all. ### Unit-3: Shell Introduction and Shell Scripting (Next 2 Questions)
- Shell scripts: Shell-specific. 11. **Integrate pipes and filters with shell variables in scripting.**
- Writing and executing: Varies. - Pipes chain commands, filters process, vars hold data.
- Shell variables: Handled. - Example: VAR=$(ls | grep txt).
- System calls: Accessed. - Shells: Bash.
- Using system calls: Similar. - Various editors: Vi.
- Pipes and filters: Supported. - Different modes: Edit.
- Choose based on needs. (Word count: 376) - Shell scripts: Use.
- Writing and executing: Run.
8. **Explain the role of editors in shell scripting, with examples of vi modes.** - System calls: In pipes.
- Editors like vi create scripts. - Using system calls: With vars.
- Vi modes: Command for navigation, insert for writing. - Enhances data flow. (Word count: 384)
- Examples: :w save, i insert.
- Shells: Integrate editors.
- Various types: Vi is standard. 12. **Discuss the evolution of shells and their impact on UNIX scripting.**
- Shell scripts: Edited. - From sh to Bash, added features.
- Writing and executing: Post-edit. - Impact: Powerful scripts.
- Shell variables: Edited. - Various editors: Evolved.
- System calls: In scripts. - Different modes in vi: Standard.
- Using system calls: Edited. - Shell scripts: Improved.
- Pipes and filters: In scripts. - Writing and executing: Easier.
- Aids development. (Word count: 378) - Shell variables: More.
- System calls: Accessible.
9. **Describe using system calls in shell scripts, with practical examples.** - Using system calls: Better.
- Use exec to replace process, e.g., exec ls. - Pipes and filters: Enhanced.
- Examples: Fork via subshells. - Modern UNIX relies on them. (Word count: 386)
- Shells: Enable. ### Unit-4: Unix Control Structures and Utilities (First 5 Questions)
- Various editors: Write calls. 1. **Explain decision making in shell scripts using if-else constructs, with examples and their role
- Different modes in vi: Edit. in automation.**
- Shell scripts: Incorporate. - If-else in Bash uses syntax like if [ condition ]; then commands; else commands; fi, evaluating
- Writing and executing: Run calls. conditions with operators like -eq for equality or -f for file existence.
- Shell variables: Pass. - Examples: if [ $num -gt 10 ]; then echo "High"; else echo "Low"; fi checks a variable.
- Pipes and filters: With calls. - Role in automation: Enables conditional execution, e.g., backing up files only if they exist,
- Low-level control. (Word count: 380) reducing errors in scripts.
- Switch (case) complements with case $var in pattern) commands;; esac for multi-branch decisions.
10. **How do shell variables enhance scripting in UNIX?** - Loops: If-else integrates with for/while for iterative checks.
- Store data, e.g., PATH for paths. - Functions: Can contain if-else for modular logic.
- Enhance: Dynamic scripts. - Utility programs: If-else scripts use cut to parse data before decisions.
- Shells: Support. - Cut: Extracts fields, e.g., cut -d: -f1 /etc/passwd.
- Various editors: Define. - Paste: Joins files, used in conditional outputs.
- Different modes in vi: Modify. - Join: Merges on keys, for data-driven decisions.
- Shell scripts: Use. - Tr: Translates characters, e.g., tr 'a-z' 'A-Z' in conditions.
- Writing and executing: Variables active. - Uniq: Removes duplicates, aiding unique checks.
- Grep: Searches patterns, e.g., if grep "error" [Link]; then alert. - Examples: backup() { if [ -f $1 ]; then cp $1 backup; fi; } called as backup [Link].
- Pattern matching utility: Grep excels in scripts for validation. - Decision making: Functions use if-else internally.
- This structure makes scripts intelligent and adaptable. (Word count: 412) - Switch: Functions can include case.
- Loops: Functions contain for/while.
2. **Discuss the switch (case) statement in shell scripts, comparing it to if-else for handling - Utility programs: Functions wrap utilities like cut.
multiple conditions.** - Cut: Functions extract data.
- Case uses case $var in pattern1) commands;; pattern2) commands;; esac, matching strings or globs like - Paste: Functions format outputs.
* for wildcards. - Join: Functions merge.
- Comparison: If-else is flexible for complex conditions, case is cleaner for enumerated options, e.g., - Tr: Functions translate.
menu selections. - Uniq: Functions dedupe.
- Examples: case $choice in 1) echo "Option 1";; 2) echo "Option 2";; esac. - Grep: Functions search.
- Decision making: Case handles branches efficiently. - Pattern matching: Grep in functions.
- Loops: Case can be inside loops for repeated choices. - Promotes modularity in scripts. (Word count: 378)
- Functions: Encapsulate case logic.
- Utility programs: Case scripts use paste for output formatting. 5. **Discuss the cut utility in UNIX, with examples of its use in shell scripts and control structures.**
- Cut: Parses input for case patterns. - Cut extracts fields/characters from lines, e.g., cut -d' ' -f1 [Link] for first word.
- Paste: Combines data post-decision. - In scripts: Used in loops to process columns, or if-else to check fields.
- Join: Merges files based on case outcomes. - Examples: for line in $(cut -f2 [Link]); do echo $line; done.
- Tr: Modifies strings for matching. - Decision making: If cut output matches, proceed.
- Uniq: Ensures unique options. - Switch: Case on cut results.
- Grep: Filters for case inputs. - Loops: Iterate over cut fields.
- Pattern matching: Grep integrates with case for searches. - Functions: Cut inside functions.
- Preferred for readability in multi-option scripts. (Word count: 398) - Utility programs: Core tool.
- Paste: Complements cut for joining.
- Join: Merges cut data.
3. **Describe loops in shell scripting, including for, while, and until, with examples of their use in - Tr: Translates cut output.
control structures.** - Uniq: Dedupes cut lines.
- For loop: for var in list; do commands; done, iterates over items like files. - Grep: Searches cut results.
- While: while [ condition ]; do commands; done, runs until false. - Pattern matching: Grep with cut.
- Until: until [ condition ]; do commands; done, runs until true. - Versatile for text manipulation. (Word count: 372)
- Examples: for file in *.txt; do echo $file; done lists files.
- Decision making: Loops combine with if for conditional iterations. ### Unit-4: Unix Control Structures and Utilities (Next 5 Questions)
- Switch: Loops can contain case for selections. 6. **Explain the paste utility and its integration with loops in shell scripting.**
- Functions: Loops inside functions for reusability. - Paste merges lines from files, e.g., paste file1 file2 for side-by-side.
- Utility programs: Loops process output from cut. - Integration: Loops use paste to combine outputs iteratively.
- Cut: Loops extract fields repeatedly. - Examples: while read line; do paste <(echo $line) [Link]; done.
- Paste: Loops join multiple files. - Decision making: If paste succeeds, continue.
- Join: Loops merge data sets. - Switch: Case on paste formats.
- Tr: Loops apply translations. - Functions: Paste in functions.
- Uniq: Loops remove duplicates in batches. - Utility programs: Key for merging.
- Grep: Loops search iteratively. - Cut: Paste after cutting.
- Pattern matching: Grep in loops for dynamic searches. - Join: Similar to paste.
- Essential for repetitive tasks in automation. (Word count: 386) - Tr: Translates pasted data.
- Uniq: Dedupes pasted lines.
4. **Explain functions in shell scripts, including how they integrate with control structures like loops - Grep: Filters pasted output.
and decisions.** - Pattern matching: Grep on paste.
- Functions defined as function_name() { commands; }, called like function_name args. - Enhances data combination. (Word count: 374)
- Integration: Functions encapsulate if-else for reusable decisions, or loops for iterative logic.
7. **Describe the join utility in UNIX, with examples in decision-making constructs.**
- Join merges files on common fields, e.g., join file1 file2 on first column. 10. **Discuss grep as a pattern matching utility, integrating with if-else in scripts.**
- In decisions: If join finds matches, execute actions. - Grep searches patterns, e.g., grep "error" [Link].
- Examples: if join [Link] [Link] > /dev/null; then echo "Matches"; fi. - With if-else: if grep -q "success" file; then echo "OK"; else echo "Fail"; fi.
- Loops: Join in loops for batch merges. - Examples: Conditional logging.
- Switch: Case on join results. - Loops: Grep in iterations.
- Functions: Join encapsulated. - Switch: Case on grep matches.
- Utility programs: For relational data. - Functions: Grep encapsulated.
- Cut: Prepares fields for join. - Utility programs: Core search.
- Paste: Alternative to join. - Cut: Grep on cut fields.
- Tr: Cleans data for join. - Paste: Grep pasted data.
- Uniq: Ensures unique keys. - Join: Grep joined.
- Grep: Searches joined data. - Tr: Grep after tr.
- Pattern matching: Grep with join. - Uniq: Grep uniques.
- Useful for database-like operations. (Word count: 376) - Pattern matching: Grep's strength.
- Powerful for validation. (Word count: 382)
8. **Discuss the tr utility for character translation, and its use with functions in scripts.**
- Tr translates/replaces characters, e.g., tr 'a-z' 'A-Z' < [Link] for uppercase. ### Unit-4: Unix Control Structures and Utilities (Next 2 Questions)
- With functions: Functions use tr for string manipulation. 11. **Integrate multiple utilities like cut, paste, and grep in control structures.**
- Examples: uppercase() { tr 'a-z' 'A-Z'; } called as echo "hello" | uppercase. - Combine: cut -f1 [Link] | grep "key" | paste - [Link].
- Decision making: If tr changes output, decide. - In structures: Loops process, if-else checks.
- Switch: Case on translated strings. - Examples: Script for data extraction.
- Loops: Tr in iterative translations. - Decision making: If combined output exists.
- Utility programs: Text processing. - Switch: Case on results.
- Cut: Tr on cut fields. - Functions: Wrap combinations.
- Paste: Tr on pasted data. - Utility programs: Synergistic.
- Join: Tr for join prep. - Join: Add to chain.
- Uniq: Tr before deduping. - Tr: Translate in chain.
- Grep: Tr for case-insensitive. - Uniq: Dedupe.
- Pattern matching: Grep after tr. - Pattern matching: Grep central.
- Simplifies text transformations. (Word count: 378) - Enhances scripting power. (Word count: 384)
12. **Compare control structures and utilities for efficient UNIX scripting.**
- Structures like if-else for logic, loops for repetition. - Utilities like grep for search, cut for extract.
9. **Explain the uniq utility and its role in loops for data processing.** - Comparison: Structures control flow, utilities process data. - Examples: Combined for automation.
- Uniq removes adjacent duplicates, e.g., sort [Link] | uniq. - Decision making: If-else with utilities. - Switch: With grep. - Loops: With cut. - Functions: Contain
- In loops: Loops process unique lines. both.
- Examples: for unique in $(sort [Link] | uniq); do echo $unique; done. - Utility programs: Essential tools. - Paste: For merging. - Join: For relations. - Tr: For translation.
- Decision making: If uniq reduces lines, act. - Uniq: For uniqueness. - Grep: For patterns.
- Switch: Case on unique values. - Optimizes scripts. (Word count: 386)
- Functions: Uniq in functions.
- Utility programs: Deduplication.
- Cut: Uniq on cut output.
- Paste: Uniq on pasted.
- Join: Uniq keys.
- Tr: Uniq after translation.
- Grep: Uniq results.
- Pattern matching: Grep for uniques.
- Ensures clean data. (Word count: 380)