Unix and Shell Programming
Comprehensive exam revision notes for BCA-204N Unit 5 (Control Structures, Functions & System Administration). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Unix and Shell Programming
Control Structures, Functions & System Administration
Core Definitions & Key Concepts
What is the syntax of the if-then-elif-else-fi structure in bash
1if [ condition ]; then2 # commands3elif [ condition2 ]; then4 # commands5else6 # commands7fiList the primary integer comparison operators used inside bash [ ] test brackets
-eq: Equal to (if [ $a -eq $b ])-ne: Not equal to-gt: Greater than-lt: Less than-ge: Greater than or equal to-le: Less than or equal to
What do -f, -d, and -s test operators do for files
-f file: True if file exists and is a regular file.-d file: True if file exists and is a directory.-s file: True if file exists and has size greater than zero (not empty).
What is the difference between while and until loops in shell scripts
while [ condition ]: Executes loop body as long as the condition evaluates to TRUE.until [ condition ]: Executes loop body as long as the condition evaluates to FALSE (stops when true).
How are functions declared and called in bash
1function_name() {2 echo "Param 1: $1, Param 2: $2"3 return 04}5# Calling the function:6function_name "arg1" "arg2"What file stores user account credentials and password hashes in Unix
/etc/passwd stores basic account info (username, UID, GID, home dir, shell). Encrypted password hashes are protected inside /etc/shadow (readable only by root).
The five time/date fields in a crontab schedule entry
Syntax: * * * * * command_to_execute
- Minute (0–59)
- Hour (0–23)
- Day of Month (1–31)
- Month (1–12)
- Day of Week (0–7, where 0 and 7 = Sunday)
What command creates a compressed backup archive (.tar.gz) of a directory
tar -czvf backup.tar.gz /home/project
-c: Create new archive-z: Compress with gzip-v: Verbose output-f: Output file name
Conceptual & Architectural Analysis
The case-esac Statement in Bash with a Menu-Driven Script Example
case ... esac Multiway Branching
Matches a variable against multiple pattern alternatives:
read -p "Enter service action [start|stop|restart|status]: " action
case $action in
start)
echo "Starting Apache HTTP service..."
sudo systemctl start apache2
;;
stop)
echo "Stopping Apache HTTP service..."
sudo systemctl stop apache2
;;
restart)
echo "Restarting Apache HTTP service..."
sudo systemctl restart apache2
;;
status)
sudo systemctl status apache2
;;
*)
echo "Invalid action! Usage: {start|stop|restart|status}"
exit 1
;;
esacUser Administration in Unix: useradd, passwd, usermod, and userdel
| Command | Action |
|---|---|
sudo useradd -m -s /bin/bash rohan | Creates user rohan, creates home dir (-m), sets default shell (-s) |
sudo passwd rohan | Sets or changes user password |
sudo usermod -aG sudo,developers rohan | Appends user to secondary groups (-aG) |
sudo userdel -r rohan | Deletes user account and removes home directory (-r) |
/etc/passwd | Colon-separated user account registry |
/etc/shadow | Shadow password file holding salt and SHA-512 hashes |
Cron Scheduling with 4 Practical Crontab Examples
Cron Job Examples (crontab -e)
1# Format: Minute Hour Day_of_Month Month Day_of_Week Command2
3# 1. Run database backup every night at 2:30 AM430 2 * * * /backup/scripts/backup_db.sh5
6# 2. Run log cleaner every Sunday at 4:00 AM70 4 * * 0 /usr/local/bin/clean_logs.sh8
9# 3. Check server health every 15 minutes during work hours (9 AM - 5 PM, Mon-Fri)10*/15 9-17 * * 1-5 /opt/monitor/health_check.sh11
12# 4. Run monthly billing script on 1st of every month at midnight130 0 1 * * /billing/generate_invoices.shUnix Backup and Archive Utilities (tar, gzip, bzip2)
- `tar` (Tape Archive): Packages multiple files into a single tape archive without compression.
- `gzip` / `gunzip`: Fast compression algorithm generating
.gzfiles. - Combined Tarball Operations:
- Create compressed archive:
tar -czvf project.tar.gz ./project/ - Extract archive:
tar -xzvf project.tar.gz -C /target/dir/ - List archive contents without extracting:
tar -tzvf project.tar.gz
In-Depth Analysis & Implementation
Develop a Complete Enterprise Backup Shell Script with Logging, Compression, Rotation, and Crontab Integration
#!/bin/bash
"""
MJPRU Examination Model Solution: Unit 5
Automated Enterprise Backup and Directory Rotation System
"""
# Configuration
SOURCE_DIR="/var/www/html"
BACKUP_DIR="/backup/web_archives"
LOG_FILE="/var/log/sys_backup.log"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
ARCHIVE_NAME="web_backup_${TIMESTAMP}.tar.gz"
RETENTION_DAYS=7
# Ensure backup directory exists
mkdir -p "$BACKUP_DIR"
log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
log_message "=== Backup Job Initiated ==="
log_message "Source: $SOURCE_DIR | Target: $BACKUP_DIR/$ARCHIVE_NAME"
# Verify source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
log_message "FATAL ERROR: Source directory $SOURCE_DIR does not exist!"
exit 1
fi
# Create compressed archive
tar -czf "$BACKUP_DIR/$ARCHIVE_NAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")" 2>> "$LOG_FILE"
if [ $? -eq 0 ]; then
FILE_SIZE=$(du -h "$BACKUP_DIR/$ARCHIVE_NAME" | cut -f1)
log_message "SUCCESS: Backup created ($FILE_SIZE)."
else
log_message "ERROR: Tar backup failed!"
exit 2
fi
# Rotation: Delete archives older than retention period
log_message "Cleaning backups older than $RETENTION_DAYS days..."
find "$BACKUP_DIR" -type f -name "web_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
log_message "=== Backup Job Finished Successfully ===\n"
exit 0Write a Shell Script Demonstrating Function Recursion to Calculate Factorial and Fibonacci Numbers
1#!/bin/bash2# Recursive Functions in Shell Scripting3
4# 1. Recursive Factorial Function5factorial() {6 local n=$17 if [ $n -le 1 ]; then8 echo 19 else10 local prev=$(factorial $(( n - 1 )))11 echo $(( n * prev ))12 fi13}14
15# 2. Recursive Fibonacci Function16fibonacci() {17 local n=$118 if [ $n -le 0 ]; then19 echo 020 elif [ $n -eq 1 ]; then21 echo 122 else23 local f1=$(fibonacci $(( n - 1 )))24 local f2=$(fibonacci $(( n - 2 )))25 echo $(( f1 + f2 ))26 fi27}28
29read -p "Enter a number (n): " num30
31fact_res=$(factorial $num)32echo "Factorial of $num ($num!) = $fact_res"33
34echo -n "Fibonacci sequence up to $num terms: "35for (( i=0; i<num; i++ )); do36 val=$(fibonacci $i)37 echo -n "$val "38done39echo ""The Complete Unix System Boot Process from BIOS/UEFI to Login Prompt
The 6 Stages of the Unix/Linux Boot Process
+-------------+ +-------------+ +-------------+ +-------------+ +-------------+ +-------------+
| 1. BIOS | --> | 2. MBR | --> | 3. GRUB | --> | 4. Kernel | --> | 5. Systemd/ | --> | 6. Login |
| POST | | Bootloader | | Boot Loader | | Initial RAM | | Init | | Prompt |
+-------------+ +-------------+ +-------------+ +-------------+ +-------------+ +-------------+- BIOS / UEFI: Executes Power-On Self-Test (POST), checks hardware integrity, searches bootable storage drive.
- MBR (Master Boot Record): Loads primary boot code from sector 0 of boot drive (512 bytes).
- GRUB Bootloader: Presents operating system selection menu and loads chosen kernel binary (
vmlinuz) andinitramfsinto RAM. - Kernel Initialization: Mounts root file system read-only, probes hardware devices, initializes virtual memory and page tables.
- Init / Systemd (PID 1): The ancestor of all processes. Mounts
/etc/fstab, launches system services, brings system to target runlevel. - Login Display: Spawns
getty/ display manager, prompts for credentials, and spawns login shell upon successful authentication.
Important Exam Points & Quick Revision
Be ready to write full crontab entries, explain the 6 boot stages, and implement backup shell scripts with error checking.
100% left on this page — finishing it closes the gap for Control Structures, Functions & System Administration.
Control Structures, Functions & System Administration still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.