Skip to content
Unit 5 Syllabus Note· Unix and Shell Programming

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

BASH
1if [ condition ]; then
2 # commands
3elif [ condition2 ]; then
4 # commands
5else
6 # commands
7fi

List 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

BASH
1function_name() {
2 echo "Param 1: $1, Param 2: $2"
3 return 0
4}
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

  1. Minute (0–59)
  2. Hour (0–23)
  3. Day of Month (1–31)
  4. Month (1–12)
  5. 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:

System Architecture / Concept DiagramHorizontal Scroll Enabled
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
        ;;
esac

User Administration in Unix: useradd, passwd, usermod, and userdel

CommandAction
sudo useradd -m -s /bin/bash rohanCreates user rohan, creates home dir (-m), sets default shell (-s)
sudo passwd rohanSets or changes user password
sudo usermod -aG sudo,developers rohanAppends user to secondary groups (-aG)
sudo userdel -r rohanDeletes user account and removes home directory (-r)
/etc/passwdColon-separated user account registry
/etc/shadowShadow password file holding salt and SHA-512 hashes

Cron Scheduling with 4 Practical Crontab Examples

Cron Job Examples (crontab -e)

CRON
1# Format: Minute Hour Day_of_Month Month Day_of_Week Command
2
3# 1. Run database backup every night at 2:30 AM
430 2 * * * /backup/scripts/backup_db.sh
5
6# 2. Run log cleaner every Sunday at 4:00 AM
70 4 * * 0 /usr/local/bin/clean_logs.sh
8
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.sh
11
12# 4. Run monthly billing script on 1st of every month at midnight
130 0 1 * * /billing/generate_invoices.sh

Unix 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 .gz files.
  • 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

System Architecture / Concept DiagramHorizontal Scroll Enabled
#!/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 0

Write a Shell Script Demonstrating Function Recursion to Calculate Factorial and Fibonacci Numbers

BASH
1#!/bin/bash
2# Recursive Functions in Shell Scripting
3
4# 1. Recursive Factorial Function
5factorial() {
6 local n=$1
7 if [ $n -le 1 ]; then
8 echo 1
9 else
10 local prev=$(factorial $(( n - 1 )))
11 echo $(( n * prev ))
12 fi
13}
14
15# 2. Recursive Fibonacci Function
16fibonacci() {
17 local n=$1
18 if [ $n -le 0 ]; then
19 echo 0
20 elif [ $n -eq 1 ]; then
21 echo 1
22 else
23 local f1=$(fibonacci $(( n - 1 )))
24 local f2=$(fibonacci $(( n - 2 )))
25 echo $(( f1 + f2 ))
26 fi
27}
28
29read -p "Enter a number (n): " num
30
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++ )); do
36 val=$(fibonacci $i)
37 echo -n "$val "
38done
39echo ""

The Complete Unix System Boot Process from BIOS/UEFI to Login Prompt

The 6 Stages of the Unix/Linux Boot Process

System Architecture / Concept DiagramHorizontal Scroll Enabled
+-------------+     +-------------+     +-------------+     +-------------+     +-------------+     +-------------+
|   1. BIOS   | --> |   2. MBR    | --> |   3. GRUB   | --> |  4. Kernel  | --> | 5. Systemd/ | --> |  6. Login   |
|    POST     |     |  Bootloader |     | Boot Loader |     | Initial RAM |     |    Init     |     |   Prompt    |
+-------------+     +-------------+     +-------------+     +-------------+     +-------------+     +-------------+
  1. BIOS / UEFI: Executes Power-On Self-Test (POST), checks hardware integrity, searches bootable storage drive.
  2. MBR (Master Boot Record): Loads primary boot code from sector 0 of boot drive (512 bytes).
  3. GRUB Bootloader: Presents operating system selection menu and loads chosen kernel binary (vmlinuz) and initramfs into RAM.
  4. Kernel Initialization: Mounts root file system read-only, probes hardware devices, initializes virtual memory and page tables.
  5. Init / Systemd (PID 1): The ancestor of all processes. Mounts /etc/fstab, launches system services, brings system to target runlevel.
  6. 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.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Control Structures, Functions & System Administration.

Weak topic hint

Control Structures, Functions & System Administration still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.