0% found this document useful (0 votes)
3 views15 pages

OS Shell Scripting DarkMode

This document serves as a study guide for beginners on shell scripting, covering essential concepts, syntax, and practical examples including scripts for prime number checks, leap year validation, palindrome verification, Armstrong number identification, Fibonacci series generation, and decimal to binary conversion. It includes detailed explanations, annotated code, and a section on common viva questions and answers related to shell scripting. The guide emphasizes the importance of understanding the shell's function as an interface between the user and the operating system.

Uploaded by

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

OS Shell Scripting DarkMode

This document serves as a study guide for beginners on shell scripting, covering essential concepts, syntax, and practical examples including scripts for prime number checks, leap year validation, palindrome verification, Armstrong number identification, Fibonacci series generation, and decimal to binary conversion. It includes detailed explanations, annotated code, and a section on common viva questions and answers related to shell scripting. The guide emphasizes the importance of understanding the shell's function as an interface between the user and the operating system.

Uploaded by

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

Operating Systems Lab

Assignment 3 — Shell Scripting Study Guide

Prime · Leap Year · Palindrome · Armstrong · Fibonacci · Decimal → Binary

Written for beginners — complete theory, annotated code, and 25+


viva Q&As.
Part 0: What Is Shell Scripting? — The Big Picture
Before we look at a single line of code, we need to answer a fundamental question: what exactly is a shell,
and why do we write scripts for it? If you skip this section, the syntax in your assignments will feel like
random symbols.

0.1 What Is a Shell?


When you open a terminal on Linux and type a command like ls or cd Documents, you are talking to the
shell. The shell is a program that reads what you type, interprets it, and sends the appropriate instructions
to the OS kernel. Think of it as a translator sitting between you (a human) and the OS (a machine).

Analogy: The OS kernel is like a powerful engine inside a car. You do not control the engine directly
— you use the steering wheel and pedals. The shell is that interface: it translates your
human-readable commands into precise instructions the engine can act on.

0.2 What Is a Shell Script?


A shell script is simply a text file full of shell commands, saved with a .sh extension, that you can run all at
once. Instead of typing ten commands one by one in a terminal, you write them in a file and the shell
executes them in sequence. Your assignments use Bash (Bourne Again SHell), the most common shell
on Linux systems.

0.3 The Shebang Line — #!/bin/bash

#!/bin/bash
# This is ALWAYS the first line of every Bash script.
# The #! tells the OS: 'use the program at this path to run this file'.
# Without it, the OS doesn't know HOW to interpret the script.

0.4 Essential Bash Concepts

Variables

name='Alice' # Assign a value — NO spaces around the = sign


echo $name # Use the variable by putting $ before its name
num=42
echo $num # Output: 42

The most critical rule: no spaces around the = sign when assigning. Writing num = 42 is wrong in Bash
— it tries to run a command called 'num'.
Reading User Input

echo 'Enter your name:'


read name # Stores whatever the user types into $name
echo "Hello, $name" # Double quotes allow $variable expansion

Arithmetic — The $(( )) Syntax


Bash does not automatically perform arithmetic. To do math, you must wrap the expression in $(( )). You
will see this in every one of your six scripts.

a=10 ; b=3
echo $((a + b)) # Addition: 13
echo $((a - b)) # Subtraction: 7
echo $((a * b)) # Multiplication: 30
echo $((a / b)) # Division: 3 (integer — remainder dropped)
echo $((a % b)) # Modulo: 1 (remainder of 10 ÷ 3)

Conditionals — if [ ] and (( ))

# Square bracket syntax — comparison flags for numbers:


if [ $num -eq 5 ] # -eq = equals | -ne = not equal | -lt -le -gt -ge
then
echo 'Five!'
fi # 'fi' closes the if block (it is just 'if' backwards)
# Double parenthesis — natural arithmetic operators, like C/Java:
if (( num % 2 == 0 ))
then
echo 'Even!'
fi

Loops

# C-style for loop:


for (( i=1; i<=5; i++ ))
do
echo $i
done
# While loop — runs as long as condition is true:
while [ $num -gt 0 ]
do
num=$((num - 1)) # Bash has no num-- — you must write this manually
done
exit vs break: break only exits the current loop — the script continues running. exit terminates the
entire script immediately. The prime number script uses exit so it stops the moment a factor is found,
preventing any further output.
Part 1: Script 1 — Prime Number Check

1.1 What Is a Prime Number?


A prime number is any integer greater than 1 that has no divisors other than 1 and itself. The number 7 is
prime because nothing divides it evenly except 1 and 7. The number 6 is not prime because 2 divides it
evenly (6 ÷ 2 = 3). By definition, 0 and 1 are never prime.

1.2 The Algorithm


To check if N is prime, we try dividing it by every integer from 2 up to N/2. If any division produces a
remainder of zero (using modulo %), N has a factor and is not prime. If none divide evenly, N is prime. We
only need to go up to N/2 because any factor larger than N/2 would require a corresponding factor smaller
than 2, which is impossible for integers.

1.3 Annotated Code

#!/bin/bash
echo "Enter a number:"
read num
# Numbers <= 1 are never prime — handle this edge case immediately
if [ $num -le 1 ]
then
echo "Not Prime"
exit # Stop the entire script right here
fi
# Try every possible divisor from 2 up to num/2
for (( i=2; i<=num/2; i++ ))
do
if [ $((num % i)) -eq 0 ] # If remainder is 0, i is a factor
then
echo "Not Prime"
exit # Found a factor — no need to check further
fi
done
# If we reach this line, no factor was ever found
echo "Prime"

1.4 Manual Trace for num = 7 and num = 9


num = 7: Greater than 1, so first check passes. Loop runs for i = 2, 3 (since 7/2 = 3 in integer division). 7
% 2 = 1, 7 % 3 = 1. No factor found. Output: Prime.
num = 9: Greater than 1. Loop runs for i = 2, 3, 4. 9 % 2 = 1 (ok), 9 % 3 = 0 — remainder is zero! Script
immediately prints Not Prime and exits.

Part 2: Script 2 — Leap Year Check

2.1 The Leap Year Rule

A year is a Leap Year if:


→ It is divisible by 400 (e.g. 1600, 2000, 2400) OR
→ It is divisible by 4 AND not divisible by 100 (e.g. 2024, 1996)
Trap: Years divisible by 100 but NOT by 400 are NOT leap years. So 1900 is not a leap year, but
2000 is.

2.2 Annotated Code

#!/bin/bash
echo "Enter a year:"
read year
# (( )) lets us use natural operators: || = OR, && = AND, == and !=
if (( (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) ))
then
echo "Leap Year"
else
echo "Not a Leap Year"
fi

2.3 Truth Table


Year % 400 == 0? % 4 == 0? % 100 == 0? Leap Year?

2000 Yes Yes Yes YES — divisible by 400

1900 No Yes Yes NO — div by 100 but not


400

2024 No Yes No YES — div by 4, not 100

2023 No No No NO — not divisible by 4


Part 3: Script 3 — Palindrome Number Check

3.1 What Is a Palindrome?


A palindrome reads the same forwards and backwards. 121, 1331, and 12321 are palindromes. 123 is not,
because reversed it is 321. The algorithm mathematically reverses the digits and compares the result to
the original.

3.2 Digit-Reversal Trace for num = 121


Step num digit = num % 10 reverse = rev*10 + digit num = num / 10

Start 121 — 0 —

1 121 1 0×10+1 = 1 12

2 12 2 1×10+2 = 12 1

3 1 1 12×10+1 = 121 0

End 0 (loop stops) — reverse = 121 == original ✓ Palindrome

3.3 Corrected Annotated Code

Bug in original: Q3 and Q5 in your assignment use capitalised keywords like Echo, While, Do, If,
Fi. Bash is case-sensitive — these must be lowercase. The corrected version is below.

#!/bin/bash
echo "Enter a number:"
read num
original=$num # Save a copy BEFORE the loop destroys $num
reverse=0
while [ $num -gt 0 ]
do
digit=$((num % 10)) # Extract last digit
reverse=$((reverse * 10 + digit)) # Prepend digit to reverse
num=$((num / 10)) # Remove last digit from num
done
if [ $original -eq $reverse ]
then
echo "Palindrome"
else
echo "Not Palindrome"
fi
Part 4: Script 4 — Armstrong Number Check

4.1 What Is an Armstrong Number?


An Armstrong number (Narcissistic number) is a number where the sum of the cubes of its individual digits
equals the number itself. Classic examples: 153 = 1³+5³+3³ = 1+125+27 = 153, and 370 = 3³+7³+0³ =
27+343+0 = 370.

4.2 Annotated Code

#!/bin/bash
echo "Enter a number:"
read num
original=$num # Save before loop modifies num
sum=0
while [ $num -gt 0 ]
do
digit=$((num % 10)) # Extract last digit
sum=$((sum + digit*digit*digit)) # Add cube of digit to sum
num=$((num / 10)) # Remove last digit
done
if [ $sum -eq $original ]
then
echo "Armstrong Number"
else
echo "Not an Armstrong Number"
fi

4.3 Trace for num = 153


Step num digit digit³ sum

Start 153 — — 0

1 153 3 27 27

2 15 5 125 152

3 1 1 1 153

End 0 — — 153 == 153 ✓ Armstrong


Part 5: Script 5 — Fibonacci Series

5.1 What Is the Fibonacci Series?


Each number in the series is the sum of the two before it, starting from 0 and 1: 0, 1, 1, 2, 3, 5, 8, 13, 21,
34 ... The algorithm tracks two variables a (current) and b (next), prints a, then shifts both forward using a
temporary variable.

5.2 Corrected Annotated Code

#!/bin/bash
echo "Enter number of terms:"
read n
a=0 # First Fibonacci number
b=1 # Second Fibonacci number
echo "Fibonacci Series:"
for (( i=1; i<=n; i++ ))
do
echo -n "$a " # -n suppresses the newline, stays on same line
temp=$((a + b)) # Calculate NEXT term BEFORE overwriting a
a=$b # Shift a forward
b=$temp # Shift b forward to the new next term
done
echo # Final newline after all terms are printed

5.3 Why temp Is Necessary


If you wrote a=$b first and then b=$((a+b)), the second line would use the NEW value of a, giving a wrong
result. The temp variable preserves the correct sum before any overwriting happens — this is the classic
swap pattern.

i Print a temp = a+b a=b b = temp

1 0 0+1=1 1 1

2 1 1+1=2 1 2

3 1 1+2=3 2 3

4 2 2+3=5 3 5

5 3 3+5=8 5 8
Part 6: Script 6 — Decimal to Binary Conversion

6.1 How the Algorithm Works


Repeatedly divide the number by 2 and collect the remainders. The remainders, read from last-to-first
(bottom-to-top), form the binary representation. The script handles this automatically by prepending each
new remainder to the front of the binary string.

Step num num % 2 (remainder) binary string

1 13 1 "1"

2 6 0 "01"

3 3 1 "101"

4 1 1 "1101"

End 0 — 1101 = 13 in binary ✓

6.2 Annotated Code

#!/bin/bash
echo "Enter a decimal number:"
read num
binary="" # Start with an empty string
while [ $num -gt 0 ]
do
rem=$((num % 2)) # Remainder is either 0 or 1
binary="$rem$binary" # PREPEND: new bit goes to the LEFT of existing bits
num=$((num / 2)) # Integer division strips the last bit
done
echo "Binary number: $binary"

Prepend not append: The division algorithm produces bits from least-significant (rightmost) to
most-significant (leftmost). By writing "$rem$binary" instead of "$binary$rem", we automatically
build the number in the correct left-to-right order.
Part 7: Complete Viva Questions & Answers
Every angle an examiner might probe — from basic syntax to deep logic traps. Questions are ordered from
basic to advanced within each category.

Category A — Shell Basics

Q: What is a shell script?

A: A shell script is a text file containing a sequence of shell commands that the Bash interpreter
executes line by line. It automates repetitive tasks without compiling.

Q: What does #!/bin/bash mean?

A: It is called a shebang. The #! tells the OS this is a script file, and /bin/bash is the path to the
interpreter. Without it, the OS does not know how to run the file.

Q: What is the difference between single and double quotes in Bash?

A: Double quotes allow variable expansion — $name is replaced by its value. Single quotes treat
everything literally — $name prints as the text '$name'.

Q: What does the read command do?

A: read pauses the script, waits for user input, and stores what is typed into the named variable.

Q: What is the modulo operator % and what does it do?

A: Modulo gives the remainder of integer division. 7 % 3 = 1 because 7 ÷ 3 = 2 remainder 1. It is


used in nearly every script to extract digits and check divisibility.

Q: What is the difference between [ ] and (( )) in conditions?

A: Square brackets [ ] use flag syntax: -eq, -lt, -gt etc. for numbers and = for strings. Double
parentheses (( )) use natural arithmetic operators: ==, <, >, &&, || — more natural for mathematical
conditions.

Q: What does echo -n do?

A: The -n flag suppresses the newline that echo normally adds, so the next output appears on the
same line. The Fibonacci script uses this to print all terms on one line.
Q: Why are Bash keywords case-sensitive?

A: Bash follows Unix conventions where all identifiers are case-sensitive. The interpreter only
recognises if, then, while, do, done, fi in lowercase. Writing 'If' causes Bash to search for a command
named 'If', which does not exist.

Category B — Script Logic

Q: Why does the prime script check up to num/2 and not num?

A: If N has a divisor d greater than N/2, then N/d would be less than 2, which is impossible for integer
divisors. So no factor of N can be larger than N/2, halving the work needed.

Q: What happens when input is 2 for the prime script?

A: 2 passes the >1 check. The loop runs for i=2 to 2/2=1 — since 2 > 1, the loop never executes.
The script reaches the final echo and correctly prints Prime.

Q: Explain the leap year condition.

A: It directly implements the Gregorian calendar rule. The first part handles century years divisible by
400 (always leap). The second handles regular years: divisible by 4 but not 100. 1900 fails because
it is divisible by 100 but not 400.

Q: Why do we save the original number before the palindrome/armstrong loop?

A: The while loop divides $num by 10 repeatedly until it becomes 0. We need the original value to
compare at the end, so we save a copy before the loop begins.

Q: What is the purpose of temp in the Fibonacci script?

A: temp stores a+b before we overwrite a. Without it, writing a=$b first would corrupt the sum
calculation on the next line. temp is the classic safe-swap variable.

Q: Why does binary conversion prepend with "$rem$binary" instead of appending?

A: Division by 2 produces the least significant bit first. Prepending places each new bit to the left of
all previous bits, which naturally builds the correct binary order.

Q: Trace the binary conversion for num = 10.

A: 10%2=0, binary='0', num=5. 5%2=1, binary='10', num=2. 2%2=0, binary='010', num=1. 1%2=1,
binary='1010', num=0. Output: 1010.
Category C — Mathematics & Edge Cases

Q: What are the four 3-digit Armstrong numbers?

A: 153, 370, 371, and 407. Verification: 3³+7³+1³ = 27+343+1 = 371 ✓

Q: What happens if palindrome input is 0?

A: The while condition [ $num -gt 0 ] is immediately false. The loop never runs, reverse stays 0,
original is 0. Since 0 == 0, the script prints Palindrome — which is reasonable.

Q: What happens if decimal-to-binary input is 0?

A: The while loop never executes, binary stays an empty string. The script prints 'Binary number: '
with nothing after it. A production script would add a special case for 0.

Q: What is the time complexity of the prime check?

A: O(N/2) which simplifies to O(N). A more efficient version checks up to √N giving O(√N), but the
N/2 approach used here is sufficient for this lab's scope.

Category D — Debugging & Common Mistakes

Q: What happens if you write num=num+1 instead of num=$((num+1))?

A: Bash assigns the literal string 'num+1' to the variable — no arithmetic happens. This is the most
common beginner Bash mistake. All arithmetic must be inside $(( )).

Q: What happens if you write if[$num -eq 0] with no spaces?

A: The command fails because Bash looks for a command literally called 'if[$num'. Square brackets
require spaces on all sides: [ $num -eq 0 ].

Q: What is the bug in Q3 and Q5 of your assignment code?

A: Both scripts use capitalised keywords: Echo, Read, While, Do, Done, If, Then, Fi. Bash only
recognises these in lowercase — capitalised versions cause 'command not found' errors.

Q: How do you run a shell script from the terminal?

A: First make it executable: chmod +x [Link]. Then run it: ./[Link]. Alternatively bypass
permissions with: bash [Link]
Part 8: Quick Revision Cheat Sheet

8.1 Bash Syntax Reference

variable=value # Assign — no spaces around =


$variable # Use variable
$((expr)) # Arithmetic
read varname # Read user input
echo "text $var" # Print with variable expansion
echo -n "text " # Print without trailing newline
[ $a -eq $b ] # Number comparison: -eq -ne -lt -le -gt -ge
(( a == b && c != d )) # Arithmetic conditions
if...then...else...fi # Conditional block
while [ cond ]; do...done # While loop
for (( i=0; i<n; i++ )); do...done # C-style for loop
exit # Terminate entire script immediately

8.2 All Six Scripts at a Glance


Script Core Idea Key Operator Watch Out For

Prime Divide by i=2..N/2; any % modulo Use exit not break; handle ≤1
remainder=0 → not prime edge case

Leap Year Div by 400 OR (div by 4 AND || and && 1900 is NOT a leap year
NOT div by 100)

Palindrome Reverse digits via %10 loop; % 10 and / 10 Save original before loop; use
compare to original lowercase

Armstrong Sum digit³ via loop; compare to digit*digit*digit Only correct for 3-digit numbers
original as written

Fibonacci Print a; temp=a+b; a=b; b=temp; Swap via temp temp prevents overwrite bug;
repeat n times echo -n inline

Dec→Binary Collect remainders of ÷2; Prepend $rem$bin Prepend not append; 0 edge
prepend each to string case unhandled

Final viva tip: For every script, be ready to: (1) explain the mathematical concept in plain English,
(2) trace through a specific example by hand step-by-step, and (3) explain why each line of code is
written the way it is. Examiners love 'what would happen if...' questions — all answers are in
Category D above.

End of Study Guide


Understand the logic, not just the syntax — that is what earns full marks.

You might also like