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

Unix and Shell Programming

Comprehensive exam revision notes for BCA-204N Unit 4 (vi Editor, Shell Environment & Scripting Fundamentals). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

Unix and Shell Programming

vi Editor, Shell Environment & Scripting Fundamentals

Core Definitions & Key Concepts

What are the three operational modes of the vi editor

  1. Command Mode: Default mode where keystrokes execute commands (delete, copy, navigate).
  2. Insert Mode: Mode for entering and typing text (entered via i, a, o).
  3. Ex / Last-Line Mode: Command-line interface at bottom of screen (entered via :).

How do you transition between modes in vi

  • Command to Insert mode: Press i (insert before cursor) or a (append after).
  • Insert back to Command mode: Press Esc.
  • Command to Ex mode: Type :.
  • Ex back to Command mode: Press Enter or Esc.

In vi, what do yy, dd, and p do

  • yy: Yanks (copies) the current line into the paste buffer.
  • dd: Deletes (cuts) the current line into the paste buffer.
  • p: Puts (pastes) the buffer contents below the current cursor line.

How do you save changes and quit the vi editor

  • Save and exit: :wq or :x or ZZ (in command mode).
  • Exit without saving (force quit): :q!.

What is the Shebang (#!/bin/bash) line at the start of a shell script

The shebang tells the kernel process loader which command interpreter binary to invoke to parse and execute the script file.

What do $? and $$ represent in a shell script

  • $?: Stores the Exit Status of the most recently executed command (0 = success, non-zero = failure).
  • $$: Stores the Process ID (PID) of the currently executing shell script.

What is Command Substitution in bash

Command substitution executes a command and replaces it with its standard output string. Syntax: $(command) or backticks ` command `.

How do you perform integer arithmetic in bash

Using $(( expression )): e.g., sum=$(( a + b )) or let sum=a+b or expr $a + $b.

Conceptual & Architectural Analysis

Essential vi Editor Navigation and Editing Commands in a Structured Table

CommandAction in vi
h, j, k, lLeft, Down, Up, Right cursor navigation
0 / $Move cursor to start of line / end of line
G / 1GMove to end of file / first line of file
i / aEnter insert mode before cursor / after cursor
o / OOpen new blank line below current / above current
xDelete single character under cursor
dw / cwDelete word / change word
u / Ctrl+rUndo last action / Redo last undo
/patternSearch forward for pattern (n next, N previous)
:%s/old/new/gGlobal search and replace throughout entire file

Standard Unix Environment Variables and the $PATH Variable

Key Environment Variables

  • `$PATH`: Colon-separated list of directories searched by the shell to find executable binaries.
  • `$HOME`: Path to the current user's home directory (/home/rohan).
  • `$USER`: Username of the logged-in account.
  • `$SHELL`: Default login shell path (/bin/bash).
  • `$PS1`: Primary shell prompt string.
BASH
1# Adding custom bin directory to $PATH persistently in ~/.bashrc
2export PATH="$HOME/bin:$PATH"

Positional Parameters and Command-Line Arguments in Shell Scripting

VariableDescription
$0Name of the executing script file
$1, $2..$9First, second through ninth positional arguments passed
${10}Tenth argument (requires curly braces for two digits)
$#Total count of positional arguments passed
$*All arguments combined into a single continuous string
$@All arguments preserved as individually quoted words "$1" "$2"
shiftShifts all arguments left by one position ($2 becomes $1)

Compare Floating-Point Arithmetic using bc versus Shell Integer Arithmetic

Bash natively supports ONLY integer arithmetic. For floating-point precision, piped calculations to `bc` (Basic Calculator) are required:

System Architecture / Concept DiagramHorizontal Scroll Enabled
# 1. Native Integer Arithmetic
a=10; b=3
int_div=$(( a / b ))
echo "Integer Division: $int_div" # Output: 3

# 2. Float Arithmetic with bc
float_div=$(echo "scale=4; $a / $b" | bc)
echo "Floating Point: $float_div"   # Output: 3.3333

In-Depth Analysis & Implementation

Write a Complete Shell Script to Implement a Interactive Calculator Supporting Float Arithmetic using bc

System Architecture / Concept DiagramHorizontal Scroll Enabled
#!/bin/bash
# University Examination Model Solution: Unit 4
# Interactive Multi-function Calculator with bc Float Support

clear
echo "=================================================="
echo "          BCA INTERACTIVE CALCULATOR (BC)"
echo "=================================================="

read -p "Enter first number (X): " num1
read -p "Enter second number (Y): " num2

echo "Select Operation:"
echo "  1. Addition (+)"
echo "  2. Subtraction (-)"
echo "  3. Multiplication (*)"
echo "  4. Division (/ with 4 decimal places)"
echo "  5. Exponentiation (^)"
read -p "Enter Choice [1-5]: " choice

case $choice in
    1)
        res=$(echo "$num1 + $num2" | bc)
        op="+"
        ;;
    2)
        res=$(echo "$num1 - $num2" | bc)
        op="-"
        ;;
    3)
        res=$(echo "$num1 * $num2" | bc)
        op="*"
        ;;
    4)
        if [ $(echo "$num2 == 0" | bc) -eq 1 ]; then
            echo "Error: Division by zero is mathematically undefined!"
            exit 1
        fi
        res=$(echo "scale=4; $num1 / $num2" | bc)
        op="/"
        ;;
    5)
        res=$(echo "$num1 ^ $num2" | bc)
        op="^"
        ;;
    *)
        echo "Invalid operation choice!"
        exit 1
        ;;
esac

echo "--------------------------------------------------"
echo "Result: $num1 $op $num2 = $res"
echo "=================================================="

Write a Shell Script to Validate User Input and Display Comprehensive System Diagnostic Information

System Architecture / Concept DiagramHorizontal Scroll Enabled
#!/bin/bash
# System Diagnostics and Health Report Script

REPORT_FILE="sys_health_$(date +%Y%m%d_%H%M%S).txt"

{
echo "===================================================="
echo "        UNIX SYSTEM HEALTH DIAGNOSTIC REPORT"
echo "        Generated On: $(date)"
echo "===================================================="

echo -e "\n1. HOSTNAME & KERNEL INFORMATION:"
echo "Hostname: $(hostname)"
echo "Kernel:   $(uname -srm)"
echo "Uptime:   $(uptime -p)"

echo -e "\n2. CPU & SYSTEM LOAD:"
uptime

echo -e "\n3. MEMORY CONSUMPTION (RAM):"
free -h

echo -e "\n4. DISK STORAGE UTILIZATION:"
df -h -x tmpfs -x devtmpfs

echo -e "\n5. CURRENT LOGGED IN USERS:"
who

echo -e "\n6. TOP 5 CPU CONSUMING PROCESSES:"
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -n 6

echo "===================================================="
} | tee "$REPORT_FILE"

echo -e "\nDiagnostic report successfully written to $REPORT_FILE"

The Complete Script Execution Cycle: Subshell Spawning vs Sourcing (source / .)

Subshell Execution vs Sourcing

Execution MethodCommandMechanismVariable Retention
Direct Execution./script.sh or bash script.shSpawns a Child Subshell via fork()Child variables DIE upon script termination; cannot modify parent shell environment
Sourcing (Dot operator)source script.sh or . script.shExecutes commands inside the CURRENT Parent ShellVariables and aliases PERSIST in current active terminal session
BASH
1# Demonstration:
2# Inside env_set.sh:
3# export TARGET_DB="production_oracle"
4
5./env_set.sh
6echo $TARGET_DB # Blank! Child subshell variable disappeared!
7
8source ./env_set.sh
9echo $TARGET_DB # Prints 'production_oracle'! Persists in parent shell!

Important Exam Points & Quick Revision

Be ready to explain vi modes with a transition diagram, $* vs $@, and how bc enables float math in bash.

Your reading progress
0%

100% left on this page — finishing it closes the gap for vi Editor, Shell Environment & Scripting Fundamentals.

Weak topic hint

vi Editor, Shell Environment & Scripting Fundamentals 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.