rguLAB

OS Lab: all codes + viva

33 record programs. Copy any code; the output and viva answers are right below it.

Download PDF

First scripts

Program 01

Add two numbers

Write a shell script to add the two numbers

Run it

Algorithm

1. Start
2. Echo a prompt, then read a
3. Read b the same way
4. Sum=$((a + b)) and echo the result
5. Stop

Program

#!/bin/bash

echo "Enter the first number:"
read a

echo "Enter the second number:"
read b

sum=$((a + b))

echo "Sum of $a and $b = $sum"

Output

Input typed: 12 ⏎ 8

Enter the first number:
12
Enter the second number:
8
Sum of 12 and 8 = 20

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the first number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read a

    This line takes keyboard input. read waits for keyboard input and stores it in a.

  4. echo "Enter the second number:"

    This line prints to the terminal. echo prints text to the terminal.

  5. read b

    This line takes keyboard input. read waits for keyboard input and stores it in b.

  6. sum=$((a + b))

    $(( … )) does integer arithmetic.

  7. echo "Sum of $a and $b = $sum"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Which syntax does integer arithmetic in bash?

A. $(( a + b )). $(( )) is arithmetic expansion. $( ) runs a command instead.

Q. What does `read a` do?

A. Reads one line from the keyboard into variable a. read stores what the user types; use $a to get the value back.

Program 02

Simple interest

Write a shell script to print the simple interest of an amount along with total amount

Run it

Algorithm

1. Start
2. Read principal p, rate r, time t
3. Si=$(echo "scale=2; $p * $r * $t / 100" | bc)
4. Total=$(echo "scale=2; $p + $si" | bc) and print both
5. Stop

Program

#!/bin/bash

echo "Enter the principal amount:"
read p

echo "Enter the rate of interest (% per year):"
read r

echo "Enter the time (in years):"
read t

si=$(echo "scale=2; $p * $r * $t / 100" | bc)
total=$(echo "scale=2; $p + $si" | bc)

echo "Simple Interest = $si"
echo "Total Amount    = $total"

Output

Input typed: 5000 ⏎ 8 ⏎ 3

Enter the principal amount:
5000
Enter the rate of interest (% per year):
8
Enter the time (in years):
3
Simple Interest = 1200.00
Total Amount    = 6200.00

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. bc is the command-line calculator; bash only does integers, so bc handles decimals.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the principal amount:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read p

    This line takes keyboard input. read waits for keyboard input and stores it in p.

  4. echo "Enter the rate of interest (% per year):"

    This line prints to the terminal. echo prints text to the terminal.

  5. read r

    This line takes keyboard input. read waits for keyboard input and stores it in r.

  6. echo "Enter the time (in years):"

    This line prints to the terminal. echo prints text to the terminal.

  7. read t

    This line takes keyboard input. read waits for keyboard input and stores it in t.

  8. si=$(echo "scale=2; $p * $r * $t / 100" | bc)

    $( … ) runs a command and puts its output here (command substitution). bc is the command-line calculator; bash only does integers, so bc handles decimals. echo prints text to the terminal.

  9. total=$(echo "scale=2; $p + $si" | bc)

    $( … ) runs a command and puts its output here (command substitution). bc is the command-line calculator; bash only does integers, so bc handles decimals. echo prints text to the terminal.

  10. echo "Simple Interest = $si"

    This line prints to the terminal. echo prints text to the terminal.

  11. echo "Total Amount    = $total"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Why pipe the formula into bc?

A. Bash arithmetic is integer only; bc handles decimals. $(( 5 / 2 )) gives 2, but bc with scale=2 gives 2.50.

Q. In bc, scale=2 means…

A. Keep 2 digits after the decimal point. bc truncates to that many decimal places.

Program 09

Area of a circle

write a shell script to input Radius and print the area of the circle

Run it

Algorithm

1. Start
2. Read r
3. Area=$(echo "scale=2; 3.14 * $r * $r" | bc)
4. Echo the area
5. Stop

Program

#!/bin/bash

echo "Enter the radius of the circle:"
read r

area=$(echo "scale=2; 3.14 * $r * $r" | bc)

echo "Area of the circle = $area"

Output

Input typed: 7

Enter the radius of the circle:
7
Area of the circle = 153.86

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. bc is the command-line calculator; bash only does integers, so bc handles decimals.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the radius of the circle:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read r

    This line takes keyboard input. read waits for keyboard input and stores it in r.

  4. area=$(echo "scale=2; 3.14 * $r * $r" | bc)

    $( … ) runs a command and puts its output here (command substitution). bc is the command-line calculator; bash only does integers, so bc handles decimals. echo prints text to the terminal.

  5. echo "Area of the circle = $area"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Area of a circle =

A. πr². 2πr is the circumference (program 14).

Q. $( … ) is called…

A. Command substitution. It replaces itself with the command's output.

Program 14

Circumference of a circle

Write a shell script to print the circumference of the circle.

Run it

Algorithm

1. Start
2. Read r
3. C=$(echo "scale=2; 2 * 3.14 * $r" | bc)
4. Print c
5. Stop

Program

#!/bin/bash

echo "Enter the radius of the circle:"
read r

circumference=$(echo "scale=2; 2 * 3.14 * $r" | bc)

echo "Circumference of the circle = $circumference"

Output

Input typed: 7

Enter the radius of the circle:
7
Circumference of the circle = 43.96

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. bc is the command-line calculator; bash only does integers, so bc handles decimals.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the radius of the circle:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read r

    This line takes keyboard input. read waits for keyboard input and stores it in r.

  4. circumference=$(echo "scale=2; 2 * 3.14 * $r" | bc)

    $( … ) runs a command and puts its output here (command substitution). bc is the command-line calculator; bash only does integers, so bc handles decimals. echo prints text to the terminal.

  5. echo "Circumference of the circle = $circumference"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Circumference =

A. 2πr. With r = 7: 2 × 3.14 × 7 = 43.96.

Program 23

Full name from title and name

shell script to print full name after input name and title separately

Run it

Algorithm

1. Start
2. Read title (Mr / Ms / Dr)
3. Read name
4. Echo "$title. $name"
5. Stop

Program

#!/bin/bash

echo "Enter the title (Mr/Ms/Dr):"
read title

echo "Enter the name:"
read name

full_name="$title. $name"

echo "Full Name: $full_name"

Output

Input typed: Mr ⏎ John Smith

Enter the title (Mr/Ms/Dr):
Mr
Enter the name:
John Smith
Full Name: Mr. John Smith

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the title (Mr/Ms/Dr):"

    This line prints to the terminal. echo prints text to the terminal.

  3. read title

    This line takes keyboard input. read waits for keyboard input and stores it in title.

  4. echo "Enter the name:"

    This line prints to the terminal. echo prints text to the terminal.

  5. read name

    This line takes keyboard input. read waits for keyboard input and stores it in name.

  6. full_name="$title. $name"

    Sets the variable full_name (no spaces around = in bash).

  7. echo "Full Name: $full_name"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Joining two strings in bash is done by…

A. Writing them next to each other: "$a $b". Bash has no + for strings.

Program 19

Swap without a third variable

Write a program in shell script to swap the values without using the third variables

Run it

Algorithm

1. Start
2. Read a and b
3. A=$((a + b)); b=$((a - b)); a=$((a - b))
4. Print the swapped values
5. Stop

Program

#!/bin/bash

echo "Enter the first number (a):"
read a

echo "Enter the second number (b):"
read b

echo "Before swapping: a = $a, b = $b"

a=$((a + b))
b=$((a - b))
a=$((a - b))

echo "After swapping:  a = $a, b = $b"

Output

Input typed: 10 ⏎ 20

Enter the first number (a):
10
Enter the second number (b):
20
Before swapping: a = 10, b = 20
After swapping:  a = 20, b = 10

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the first number (a):"

    This line prints to the terminal. echo prints text to the terminal.

  3. read a

    This line takes keyboard input. read waits for keyboard input and stores it in a.

  4. echo "Enter the second number (b):"

    This line prints to the terminal. echo prints text to the terminal.

  5. read b

    This line takes keyboard input. read waits for keyboard input and stores it in b.

  6. echo "Before swapping: a = $a, b = $b"

    This line prints to the terminal. echo prints text to the terminal.

  7. a=$((a + b))

    $(( … )) does integer arithmetic.

  8. b=$((a - b))

    $(( … )) does integer arithmetic.

  9. a=$((a - b))

    $(( … )) does integer arithmetic.

  10. echo "After swapping:  a = $a, b = $b"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. After a=a+b; b=a−b; a=a−b with a=10, b=20…

A. a = 20, b = 10. A XOR swap (a^=b; b^=a; a^=b) also works.

Decisions

Program 03

Odd or even

write a shell script to input a number and check whether it is an odd or even number.

Run it

Algorithm

1. Start
2. Read n
3. If [ $((n % 2)) -eq 0 ] → even
4. Else → odd, close with fi
5. Stop

Program

#!/bin/bash

echo "Enter a number:"
read n

if (( n % 2 == 0 ))
then
    echo "$n is an Even number"
else
    echo "$n is an Odd number"
fi

Output

Input typed: 7

Enter a number:
7
7 is an Odd number

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. if (( n % 2 == 0 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  5. echo "$n is an Even number"

    This line prints to the terminal. echo prints text to the terminal.

  6. echo "$n is an Odd number"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Which operator gives the remainder?

A. %. n % 2 is 0 for even numbers.

Q. How does an if block end in bash?

A. fi. if … then … else … fi. case ends with esac, loops with done.

Program 17

Leap year

Write the shell script to input a year and check whether it is leap year or not

Run it

Algorithm

1. Start
2. Read y
3. Leap if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
4. Echo the result
5. Stop

Program

#!/bin/bash

echo "Enter a year:"
read y

if (( (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 ))
then
    echo "$y is a Leap Year"
else
    echo "$y is not a Leap Year"
fi

Output

Input typed: 2024

Enter a year:
2024
2024 is a Leap Year

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a year:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read y

    This line takes keyboard input. read waits for keyboard input and stores it in y.

  4. if (( (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  5. echo "$y is a Leap Year"

    This line prints to the terminal. echo prints text to the terminal.

  6. echo "$y is not a Leap Year"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Is 1900 a leap year?

A. No: divisible by 100 but not by 400. 2000 is a leap year because it is divisible by 400.

Program 20

Grade from marks

Write the shell script to print the grade after input the marks of four different subjects

Run it

Algorithm

1. Start
2. Read m1 m2 m3 m4 on one line
3. Avg=$(( (m1 + m2 + m3 + m4) / 4 ))
4. If / elif ladder: ≥ 90 → A, ≥ 75 → B, …
5. Stop

Program

#!/bin/bash

echo "Enter the marks of 4 subjects (out of 100):"
read m1 m2 m3 m4

total=$((m1 + m2 + m3 + m4))
percent=$((total / 4))

if (( percent >= 90 ))
then
    grade="A+"
elif (( percent >= 80 ))
then
    grade="A"
elif (( percent >= 70 ))
then
    grade="B"
elif (( percent >= 60 ))
then
    grade="C"
elif (( percent >= 50 ))
then
    grade="D"
else
    grade="F"
fi

echo "Total      = $total / 400"
echo "Percentage = $percent%"
echo "Grade      = $grade"

Output

Input typed: 85 90 78 92

Enter the marks of 4 subjects (out of 100):
85 90 78 92
Total      = 345 / 400
Percentage = 86%
Grade      = A

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the marks of 4 subjects (out of 100):"

    This line prints to the terminal. echo prints text to the terminal.

  3. read m1 m2 m3 m4

    This line takes keyboard input. read waits for keyboard input and stores it in m1, m2, m3, m4.

  4. total=$((m1 + m2 + m3 + m4))

    $(( … )) does integer arithmetic.

  5. percent=$((total / 4))

    $(( … )) does integer arithmetic.

  6. if (( percent >= 90 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  7. grade="A+"

    Sets the variable grade (no spaces around = in bash).

  8. elif (( percent >= 80 ))

    This line is a condition test. elif checks another condition when the previous one failed.

  9. grade="A"

    Sets the variable grade (no spaces around = in bash).

  10. elif (( percent >= 70 ))

    This line is a condition test. elif checks another condition when the previous one failed.

  11. grade="B"

    Sets the variable grade (no spaces around = in bash).

  12. elif (( percent >= 60 ))

    This line is a condition test. elif checks another condition when the previous one failed.

  13. grade="C"

    Sets the variable grade (no spaces around = in bash).

  14. elif (( percent >= 50 ))

    This line is a condition test. elif checks another condition when the previous one failed.

  15. grade="D"

    Sets the variable grade (no spaces around = in bash).

  16. grade="F"

    Sets the variable grade (no spaces around = in bash).

  17. echo "Total      = $total / 400"

    This line prints to the terminal. echo prints text to the terminal.

  18. echo "Percentage = $percent%"

    This line prints to the terminal. echo prints text to the terminal.

  19. echo "Grade      = $grade"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. How do you read four values typed on one line?

A. read m1 m2 m3 m4. read splits the line on spaces into each variable.

Q. elif is short for…

A. else if. if … elif … else … fi.

Program 29

Largest of three

shell script to print the largest of three input numbers

Run it

Algorithm

1. Start
2. Read a b c
3. If a ≥ b and a ≥ c → a; elif b ≥ c → b; else c
4. Print the largest
5. Stop

Program

#!/bin/bash

echo "Enter three numbers:"
read a b c

if (( a >= b && a >= c ))
then
    largest=$a
elif (( b >= a && b >= c ))
then
    largest=$b
else
    largest=$c
fi

echo "Largest of $a, $b and $c = $largest"

Output

Input typed: 15 42 27

Enter three numbers:
15 42 27
Largest of 15, 42 and 27 = 42

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter three numbers:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read a b c

    This line takes keyboard input. read waits for keyboard input and stores it in a, b, c.

  4. if (( a >= b && a >= c ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  5. largest=$a

    Sets the variable largest (no spaces around = in bash).

  6. elif (( b >= a && b >= c ))

    This line is a condition test. elif checks another condition when the previous one failed.

  7. largest=$b

    Sets the variable largest (no spaces around = in bash).

  8. largest=$c

    Sets the variable largest (no spaces around = in bash).

  9. echo "Largest of $a, $b and $c = $largest"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. How do you write AND between two tests?

A. [ $a -ge $b ] && [ $a -ge $c ]. Inside one [ ], -a also means AND, but && is clearer.

Program 18

Menu with case

Write the shell script using infinite loop to multiply and subtract the two number using case statement

Run it

Algorithm

1. Start
2. While true: show the menu, read choice
3. Case $choice in 1) multiply ;; 2) subtract ;; 3) exit 0 ;; *) invalid ;; esac
4. Done
5. Stop

Program

#!/bin/bash

while true
do
    echo
    echo "1. Multiply"
    echo "2. Subtract"
    echo "3. Exit"
    echo "Enter your choice:"
    read choice

    case $choice in
        1)
            echo "Enter two numbers:"
            read a b
            echo "$a x $b = $((a * b))"
            ;;
        2)
            echo "Enter two numbers:"
            read a b
            echo "$a - $b = $((a - b))"
            ;;
        3)
            echo "Exiting..."
            exit 0
            ;;
        *)
            echo "Invalid choice"
            ;;
    esac
done

Output

Input typed: 1 ⏎ 6 7 ⏎ 2 ⏎ 20 8 ⏎ 3


1. Multiply
2. Subtract
3. Exit
Enter your choice:
1
Enter two numbers:
6 7
6 x 7 = 42

1. Multiply
2. Subtract
3. Exit
Enter your choice:
2
Enter two numbers:
20 8
20 - 8 = 12

1. Multiply
2. Subtract
3. Exit
Enter your choice:
3
Exiting...

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. while repeats as long as the condition is true. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. case matches a value against several patterns, like switch in C. exit ends the script (0 means success).

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. while true

    This line starts a loop. while repeats as long as the condition is true. true always succeeds, so while true loops forever until a break.

  3. echo

    This line prints to the terminal. echo prints text to the terminal.

  4. echo "1. Multiply"

    This line prints to the terminal. echo prints text to the terminal.

  5. echo "2. Subtract"

    This line prints to the terminal. echo prints text to the terminal.

  6. echo "3. Exit"

    This line prints to the terminal. echo prints text to the terminal.

  7. echo "Enter your choice:"

    This line prints to the terminal. echo prints text to the terminal.

  8. read choice

    This line takes keyboard input. read waits for keyboard input and stores it in choice.

  9. case $choice in

    case matches a value against several patterns, like switch in C. in introduces the list a for loop runs over, or the value case matches.

  10. echo "Enter two numbers:"

    This line prints to the terminal. echo prints text to the terminal.

  11. read a b

    This line takes keyboard input. read waits for keyboard input and stores it in a, b.

  12. echo "$a x $b = $((a * b))"

    This line prints to the terminal. $(( … )) does integer arithmetic. echo prints text to the terminal.

  13. echo "$a - $b = $((a - b))"

    This line prints to the terminal. $(( … )) does integer arithmetic. echo prints text to the terminal.

  14. echo "Exiting..."

    This line prints to the terminal. echo prints text to the terminal.

  15. exit 0

    exit ends the script (0 means success).

  16. echo "Invalid choice"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Which ends each case branch?

A. ;;. The whole case block ends with esac.

Q. How does this infinite loop stop?

A. Choice 3 runs exit 0. while true never ends by itself.

Q. The *) branch matches…

A. Anything not matched above (default). It's like default: in a C switch.

Loops & numbers

Program 04

Factorial (loop)

write a shell script to input a number and print the factorial of that number

Run it

Algorithm

1. Start
2. Read n, set fact=1
3. While [ $n -gt 1 ]: fact=$((fact * n)), n=$((n - 1))
4. Echo the factorial
5. Stop

Program

#!/bin/bash

echo "Enter a number:"
read n

fact=1
i=1

while (( i <= n ))
do
    fact=$((fact * i))
    i=$((i + 1))
done

echo "Factorial of $n = $fact"

Output

Input typed: 5

Enter a number:
5
Factorial of 5 = 120

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. while repeats as long as the condition is true.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. fact=1

    Sets the variable fact (no spaces around = in bash).

  5. i=1

    Sets the variable i (no spaces around = in bash).

  6. while (( i <= n ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. while repeats as long as the condition is true.

  7. fact=$((fact * i))

    $(( … )) does integer arithmetic.

  8. i=$((i + 1))

    $(( … )) does integer arithmetic.

  9. echo "Factorial of $n = $fact"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. -gt inside [ ] means…

A. Greater than. -eq, -ne, -lt, -le, -gt, -ge compare integers.

Q. Why does fact start at 1, not 0?

A. Multiplying by 0 would always give 0. 1 is the multiplicative identity, and 0! = 1.

Program 05

Reverse a number

write a shell script to input a number and print the reverse of that number

Run it

Algorithm

1. Start
2. Read n, rev=0
3. Loop while n > 0: digit=$((n % 10)), rev=$((rev * 10 + digit)), n=$((n / 10))
4. Print rev
5. Stop

Program

#!/bin/bash

echo "Enter a number:"
read n

num=$n
rev=0

while (( num > 0 ))
do
    digit=$((num % 10))
    rev=$((rev * 10 + digit))
    num=$((num / 10))
done

echo "Reverse of $n = $rev"

Output

Input typed: 12345

Enter a number:
12345
Reverse of 12345 = 54321

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. while repeats as long as the condition is true.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. num=$n

    Sets the variable num (no spaces around = in bash).

  5. rev=0

    Sets the variable rev (no spaces around = in bash).

  6. while (( num > 0 ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. while repeats as long as the condition is true.

  7. digit=$((num % 10))

    $(( … )) does integer arithmetic.

  8. rev=$((rev * 10 + digit))

    $(( … )) does integer arithmetic.

  9. num=$((num / 10))

    $(( … )) does integer arithmetic.

  10. echo "Reverse of $n = $rev"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. n % 10 gives…

A. The last digit of n. 12345 % 10 = 5.

Q. n / 10 in bash arithmetic…

A. Drops the last digit (integer division). 12345 / 10 = 1234.

Program 06

Sum of digits

Write a shell script to print the sum of the digit of the input term.

Run it

Algorithm

1. Start
2. Read n, sum=0
3. While n > 0: sum += n % 10; n /= 10
4. Print sum
5. Stop

Program

#!/bin/bash

echo "Enter a number:"
read n

num=$n
sum=0

while (( num > 0 ))
do
    sum=$((sum + num % 10))
    num=$((num / 10))
done

echo "Sum of digits of $n = $sum"

Output

Input typed: 4567

Enter a number:
4567
Sum of digits of 4567 = 22

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. while repeats as long as the condition is true.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. num=$n

    Sets the variable num (no spaces around = in bash).

  5. sum=0

    Sets the variable sum (no spaces around = in bash).

  6. while (( num > 0 ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. while repeats as long as the condition is true.

  7. sum=$((sum + num % 10))

    $(( … )) does integer arithmetic.

  8. num=$((num / 10))

    $(( … )) does integer arithmetic.

  9. echo "Sum of digits of $n = $sum"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Sum of digits of 4567 is…

A. 22. 4 + 5 + 6 + 7 = 22.

Q. Which loop keeps going while a condition is true?

A. while. until is the opposite: it runs while the condition is false.

Program 11

Sum of a 3-digit number's digits

Write the shell script to print the sum of the digit of the 3 digit number

Run it

Algorithm

1. Start
2. Read n (e.g. 456)
3. D1=$((n / 100)), d2=$((n / 10 % 10)), d3=$((n % 10))
4. Print d1 + d2 + d3
5. Stop

Program

#!/bin/bash

echo "Enter a 3 digit number:"
read n

if (( n < 100 || n > 999 ))
then
    echo "Please enter a 3 digit number"
    exit 1
fi

d1=$((n / 100))
d2=$((n / 10 % 10))
d3=$((n % 10))

sum=$((d1 + d2 + d3))

echo "$d1 + $d2 + $d3 = $sum"
echo "Sum of digits of $n = $sum"

Output

Input typed: 456

Enter a 3 digit number:
456
4 + 5 + 6 = 15
Sum of digits of 456 = 15

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. exit ends the script (0 means success).

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a 3 digit number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. if (( n < 100 || n > 999 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  5. echo "Please enter a 3 digit number"

    This line prints to the terminal. echo prints text to the terminal.

  6. exit 1

    exit ends the script (0 means success).

  7. d1=$((n / 100))

    $(( … )) does integer arithmetic.

  8. d2=$((n / 10 % 10))

    $(( … )) does integer arithmetic.

  9. d3=$((n % 10))

    $(( … )) does integer arithmetic.

  10. sum=$((d1 + d2 + d3))

    $(( … )) does integer arithmetic.

  11. echo "$d1 + $d2 + $d3 = $sum"

    This line prints to the terminal. echo prints text to the terminal.

  12. echo "Sum of digits of $n = $sum"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. For n = 456, n / 10 % 10 gives…

A. 5. 456 / 10 = 45, and 45 % 10 = 5.

Program 07

Prime check

write a shell script to input a number and check whether it is a prime number or not

Run it

Algorithm

1. Start
2. Read n; n < 2 is not prime
3. For i from 2 to n/2 (or √n): if n % i == 0 → not prime
4. Use a flag to print the result
5. Stop

Program

#!/bin/bash

echo "Enter a number:"
read n

if (( n < 2 ))
then
    echo "$n is not a Prime number"
    exit 0
fi

i=2
prime=1

while (( i * i <= n ))
do
    if (( n % i == 0 ))
    then
        prime=0
        break
    fi
    i=$((i + 1))
done

if (( prime == 1 ))
then
    echo "$n is a Prime number"
else
    echo "$n is not a Prime number"
fi

Output

Input typed: 29

Enter a number:
29
29 is a Prime number

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. exit ends the script (0 means success). while repeats as long as the condition is true. break leaves the loop immediately.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. if (( n < 2 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  5. echo "$n is not a Prime number"

    This line prints to the terminal. echo prints text to the terminal.

  6. exit 0

    exit ends the script (0 means success).

  7. i=2

    Sets the variable i (no spaces around = in bash).

  8. prime=1

    Sets the variable prime (no spaces around = in bash).

  9. while (( i * i <= n ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. while repeats as long as the condition is true.

  10. if (( n % i == 0 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  11. prime=0

    Sets the variable prime (no spaces around = in bash).

  12. break

    break leaves the loop immediately.

  13. i=$((i + 1))

    $(( … )) does integer arithmetic.

  14. if (( prime == 1 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  15. echo "$n is a Prime number"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. A prime number has…

A. Exactly two factors: 1 and itself. 1 is not prime, 2 is the only even prime.

Q. Why can the loop stop at √n?

A. Any factor larger than √n pairs with one smaller than √n. If n = a × b and a ≤ b, then a ≤ √n.

Program 08

Fibonacci series

write a shell script to input a term and print the Fibonacci Series of that term

Run it

Algorithm

1. Start
2. Read n terms, a=0, b=1
3. Loop n times: print a; next=$((a + b)); a=$b; b=$next
4. Echo -n keeps terms on one line
5. Stop

Program

#!/bin/bash

echo "Enter the number of terms:"
read n

a=0
b=1

echo "Fibonacci Series of $n terms:"

for (( i = 1; i <= n; i++ ))
do
    echo -n "$a "
    c=$((a + b))
    a=$b
    b=$c
done

echo

Output

Input typed: 10

Enter the number of terms:
10
Fibonacci Series of 10 terms:
0 1 1 2 3 5 8 13 21 34

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the number of terms:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. a=0

    Sets the variable a (no spaces around = in bash).

  5. b=1

    Sets the variable b (no spaces around = in bash).

  6. echo "Fibonacci Series of $n terms:"

    This line prints to the terminal. echo prints text to the terminal.

  7. for (( i = 1; i <= n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  8. echo -n "$a "

    This line prints to the terminal. echo prints text to the terminal. -n is true when a string is not empty.

  9. c=$((a + b))

    $(( … )) does integer arithmetic.

  10. a=$b

    Sets the variable a (no spaces around = in bash).

  11. b=$c

    Sets the variable b (no spaces around = in bash).

  12. echo

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. First 6 Fibonacci terms are…

A. 0 1 1 2 3 5. Each term is the sum of the two before it.

Q. echo -n …

A. Prints without the trailing newline. So the series stays on one line.

Program 10

GCD (Euclid)

Write a shell script to print the GCD of the two input terms

Run it

Algorithm

1. Start
2. Read a and b
3. While b != 0: r=$((a % b)); a=$b; b=$r
4. A is the GCD
5. Stop

Program

#!/bin/bash

echo "Enter the first number:"
read a

echo "Enter the second number:"
read b

x=$a
y=$b

while (( y != 0 ))
do
    r=$((x % y))
    x=$y
    y=$r
done

echo "GCD of $a and $b = $x"

Output

Input typed: 48 ⏎ 18

Enter the first number:
48
Enter the second number:
18
GCD of 48 and 18 = 6

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. while repeats as long as the condition is true.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the first number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read a

    This line takes keyboard input. read waits for keyboard input and stores it in a.

  4. echo "Enter the second number:"

    This line prints to the terminal. echo prints text to the terminal.

  5. read b

    This line takes keyboard input. read waits for keyboard input and stores it in b.

  6. x=$a

    Sets the variable x (no spaces around = in bash).

  7. y=$b

    Sets the variable y (no spaces around = in bash).

  8. while (( y != 0 ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. while repeats as long as the condition is true.

  9. r=$((x % y))

    $(( … )) does integer arithmetic.

  10. x=$y

    Sets the variable x (no spaces around = in bash).

  11. y=$r

    Sets the variable y (no spaces around = in bash).

  12. echo "GCD of $a and $b = $x"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. GCD(48, 18) is…

A. 6. 48 % 18 = 12 → 18 % 12 = 6 → 12 % 6 = 0.

Q. Euclid's algorithm repeatedly replaces (a, b) with…

A. (b, a mod b). It stops when the remainder is 0.

Program 12

Odd & even sums (1–50)

Write a shell script to print the sum of odd and even numbers from 1 to 50

Run it

Algorithm

1. Start
2. For ((i=1; i<=50; i++))
3. If i % 2 == 0, add to even, else add to odd
4. Print both sums
5. Stop

Program

#!/bin/bash

odd=0
even=0

for (( i = 1; i <= 50; i++ ))
do
    if (( i % 2 == 0 ))
    then
        even=$((even + i))
    else
        odd=$((odd + i))
    fi
done

echo "Sum of odd numbers from 1 to 50  = $odd"
echo "Sum of even numbers from 1 to 50 = $even"

Output

Sum of odd numbers from 1 to 50  = 625
Sum of even numbers from 1 to 50 = 650

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. for loops over a list or a counted range. echo prints text to the terminal.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. odd=0

    Sets the variable odd (no spaces around = in bash).

  3. even=0

    Sets the variable even (no spaces around = in bash).

  4. for (( i = 1; i <= 50; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  5. if (( i % 2 == 0 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  6. even=$((even + i))

    $(( … )) does integer arithmetic.

  7. odd=$((odd + i))

    $(( … )) does integer arithmetic.

  8. echo "Sum of odd numbers from 1 to 50  = $odd"

    This line prints to the terminal. echo prints text to the terminal.

  9. echo "Sum of even numbers from 1 to 50 = $even"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Sum of even numbers from 1 to 50 is…

A. 650. 2 + 4 + … + 50 = 25 × 26 = 650; the odd sum is 625.

Q. for ((i=1; i<=50; i++)) is…

A. A C-style for loop. Bash also has the list form: for i in 1 2 3.

Program 13

Multiplication table

Write a shell script to print the multiplication table of the input term

Run it

Algorithm

1. Start
2. Read n
3. For i in 1..10: echo "$n x $i = $((n * i))"
4. Done
5. Stop

Program

#!/bin/bash

echo "Enter a number:"
read n

for (( i = 1; i <= 10; i++ ))
do
    echo "$n x $i = $((n * i))"
done

Output

Input typed: 7

Enter a number:
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter a number:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. for (( i = 1; i <= 10; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  5. echo "$n x $i = $((n * i))"

    This line prints to the terminal. $(( … )) does integer arithmetic. echo prints text to the terminal.

Viva: concepts

Q. Which keyword ends a for/while loop body?

A. done. for … do … done.

Program 21

Power without built-ins

write the shell script to print the power of an input number and bash without using any predefined function

Run it

Algorithm

1. Start
2. Read base and exp
3. Result=1; loop exp times: result=$((result * base))
4. Print result
5. Stop

Program

#!/bin/bash

echo "Enter the base:"
read base

echo "Enter the exponent:"
read exp

result=1

for (( i = 1; i <= exp; i++ ))
do
    result=$((result * base))
done

echo "$base ^ $exp = $result"

Output

Input typed: 2 ⏎ 10

Enter the base:
2
Enter the exponent:
10
2 ^ 10 = 1024

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the base:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read base

    This line takes keyboard input. read waits for keyboard input and stores it in base.

  4. echo "Enter the exponent:"

    This line prints to the terminal. echo prints text to the terminal.

  5. read exp

    This line takes keyboard input. read waits for keyboard input and stores it in exp.

  6. result=1

    Sets the variable result (no spaces around = in bash).

  7. for (( i = 1; i <= exp; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  8. result=$((result * base))

    $(( … )) does integer arithmetic.

  9. echo "$base ^ $exp = $result"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. 2 to the power 10 is…

A. 1024. Bash also has ** in $(( 2 ** 10 )), but the aim says not to use it.

Functions & patterns

Program 22

Factorial with a function

shell function to input a number and print the factorial of that number

Run it

Algorithm

1. Start
2. Factorial() { local n=$1; … echo $fact; }
3. Read num
4. Result=$(factorial $num) and print
5. Stop

Program

#!/bin/bash

factorial()
{
    local n=$1
    local fact=1

    for (( i = 2; i <= n; i++ ))
    do
        fact=$((fact * i))
    done

    echo $fact
}

echo "Enter a number:"
read n

echo "Factorial of $n = $(factorial $n)"

Output

Input typed: 6

Enter a number:
6
Factorial of 6 = 720

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. local makes a variable visible only inside the function. for loops over a list or a counted range. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. local n=$1

    $1 is the first argument passed to the function or script. local makes a variable visible only inside the function.

  3. local fact=1

    local makes a variable visible only inside the function.

  4. for (( i = 2; i <= n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  5. fact=$((fact * i))

    $(( … )) does integer arithmetic.

  6. echo $fact

    This line prints to the terminal. echo prints text to the terminal.

  7. echo "Enter a number:"

    This line prints to the terminal. echo prints text to the terminal.

  8. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  9. echo "Factorial of $n = $(factorial $n)"

    This line prints to the terminal. $( … ) runs a command and puts its output here (command substitution). echo prints text to the terminal.

Viva: concepts

Q. Inside a function, $1 is…

A. The first argument passed to it. $0 is the script, $# the argument count, $? the last exit status.

Q. Why use `local` inside the function?

A. So the variable doesn't leak into the rest of the script. Without local, every variable in bash is global.

Program 24

Star pyramid

shell script to print pyramid

Run it

Algorithm

1. Start
2. Read rows n
3. For each row i: print n − i spaces, then 2i − 1 stars
4. Echo after each row
5. Stop

Program

#!/bin/bash

echo "Enter the number of rows:"
read n

for (( i = 1; i <= n; i++ ))
do
    # Leading spaces
    for (( s = 1; s <= n - i; s++ ))
    do
        echo -n " "
    done

    # Stars
    for (( j = 1; j <= 2 * i - 1; j++ ))
    do
        echo -n "*"
    done

    echo
done

Output

Input typed: 5

Enter the number of rows:
5
    *
   ***
  *****
 *******
*********

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the number of rows:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. for (( i = 1; i <= n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  5. for (( s = 1; s <= n - i; s++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  6. echo -n " "

    This line prints to the terminal. echo prints text to the terminal. -n is true when a string is not empty.

  7. for (( j = 1; j <= 2 * i - 1; j++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  8. echo -n "*"

    This line prints to the terminal. echo prints text to the terminal. -n is true when a string is not empty.

  9. echo

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Row i of a centred pyramid has how many stars?

A. 2i − 1. 1, 3, 5, 7, …

Program 25

Number pattern

Write the shell script to print the following pattern after input term #n=3

Run it

Algorithm

1. Start
2. Read n
3. Nested loops: outer i = 1..n, inner j = 1..i
4. Echo -n $j, then a newline after each row
5. Stop

Program

#!/bin/bash
# For n = 3:
# 1
# 1 2
# 1 2 3

echo "Enter the number of terms:"
read n

for (( i = 1; i <= n; i++ ))
do
    for (( j = 1; j <= i; j++ ))
    do
        echo -n "$j "
    done
    echo
done

Output

Input typed: 3

Enter the number of terms:
3
1
1 2
1 2 3

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the number of terms:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. for (( i = 1; i <= n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  5. for (( j = 1; j <= i; j++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  6. echo -n "$j "

    This line prints to the terminal. echo prints text to the terminal. -n is true when a string is not empty.

  7. echo

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. In a nested loop, the inner loop runs…

A. Completely for every single outer iteration. That is why the work is n × n for full grids.

Program 28

Pascal's triangle

Write a shell script to input a term and print the pascal triangle of that term

Run it

Algorithm

1. Start
2. Read rows
3. Each entry: c = c × (i − j) / (j + 1), starting at 1
4. Print spaces first to centre each row
5. Stop

Program

#!/bin/bash

echo "Enter the number of terms:"
read n

for (( i = 0; i < n; i++ ))
do
    # Leading spaces to center the row
    for (( s = 0; s < n - i - 1; s++ ))
    do
        echo -n "  "
    done

    # Each value is C(i, j) = C(i, j - 1) * (i - j + 1) / j
    c=1
    for (( j = 0; j <= i; j++ ))
    do
        printf "%4d" $c
        c=$((c * (i - j) / (j + 1)))
    done

    echo
done

Output

Input typed: 5

Enter the number of terms:
5
           1
         1   1
       1   2   1
     1   3   3   1
   1   4   6   4   1

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range. printf prints with a format, like C's printf.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the number of terms:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. for (( i = 0; i < n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  5. for (( s = 0; s < n - i - 1; s++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  6. echo -n "  "

    This line prints to the terminal. echo prints text to the terminal. -n is true when a string is not empty.

  7. c=1

    Sets the variable c (no spaces around = in bash).

  8. for (( j = 0; j <= i; j++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  9. printf "%4d" $c

    printf prints with a format, like C's printf.

  10. c=$((c * (i - j) / (j + 1)))

    $(( … )) does integer arithmetic.

  11. echo

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Each inner number in Pascal's triangle is…

A. The sum of the two numbers above it. Row n holds the binomial coefficients nCk.

Arrays

Program 26

Array input & display

Write a shell script to input the array elements and display it.

Run it

Algorithm

1. Start
2. Read n
3. For i in 0..n-1: read arr[i]
4. Loop again and print arr[$i] (or ${arr[@]})
5. Stop

Program

#!/bin/bash

echo "Enter the number of elements:"
read n

echo "Enter $n elements:"
for (( i = 0; i < n; i++ ))
do
    read arr[i]
done

echo "The array elements are:"
for (( i = 0; i < n; i++ ))
do
    echo "arr[$i] = ${arr[i]}"
done

Output

Input typed: 5 ⏎ 10 ⏎ 20 ⏎ 30 ⏎ 40 ⏎ 50

Enter the number of elements:
5
Enter 5 elements:
10
20
30
40
50
The array elements are:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the number of elements:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. echo "Enter $n elements:"

    This line prints to the terminal. echo prints text to the terminal.

  5. for (( i = 0; i < n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  6. read arr[i]

    This line takes keyboard input. read waits for keyboard input and stores it in arr[i].

  7. echo "The array elements are:"

    This line prints to the terminal. echo prints text to the terminal.

  8. echo "arr[$i] = ${arr[i]}"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. ${arr[@]} gives…

A. All the elements of the array. ${#arr[@]} gives the length.

Q. Bash array indices start at…

A. 0. Same as C.

Program 27

Largest in an array

Write a shell script to print the largest element from an array

Run it

Algorithm

1. Start
2. Read the elements into arr
3. Max=${arr[0]}
4. Loop: if [ ${arr[i]} -gt $max ] then max=${arr[i]}
5. Stop

Program

#!/bin/bash

echo "Enter the number of elements:"
read n

echo "Enter $n elements:"
for (( i = 0; i < n; i++ ))
do
    read arr[i]
done

max=${arr[0]}

for (( i = 1; i < n; i++ ))
do
    if (( arr[i] > max ))
    then
        max=${arr[i]}
    fi
done

echo "Array: ${arr[*]}"
echo "Largest element = $max"

Output

Input typed: 5 ⏎ 12 ⏎ 45 ⏎ 7 ⏎ 89 ⏎ 23

Enter the number of elements:
5
Enter 5 elements:
12
45
7
89
23
Array: 12 45 7 89 23
Largest element = 89

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter the number of elements:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. echo "Enter $n elements:"

    This line prints to the terminal. echo prints text to the terminal.

  5. for (( i = 0; i < n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  6. read arr[i]

    This line takes keyboard input. read waits for keyboard input and stores it in arr[i].

  7. max=${arr[0]}

    Sets the variable max (no spaces around = in bash).

  8. for (( i = 1; i < n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  9. if (( arr[i] > max ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  10. max=${arr[i]}

    Sets the variable max (no spaces around = in bash).

  11. echo "Array: ${arr[*]}"

    This line prints to the terminal. echo prints text to the terminal.

  12. echo "Largest element = $max"

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. Why start max at arr[0] and not 0?

A. So it also works when every element is negative. Starting at 0 would wrongly return 0 for [-5, -2].

CPU scheduling

Program 15

FCFS scheduling (C)

Write A Program in c to implement the FCFS Algorithm

Run it

Algorithm

1. Start
2. Read n and each burst time
3. Wt[0] = 0; wt[i] = wt[i-1] + bt[i-1]
4. Tat[i] = wt[i] + bt[i]; print the table and the averages
5. Stop

Program

#include <stdio.h>

int main()
{
    int n, i;
    int bt[20], wt[20], tat[20];
    float total_wt = 0, total_tat = 0;

    printf("Enter number of processes: ");
    scanf("%d", &n);

    printf("Enter burst time for each process:\n");
    for (i = 0; i < n; i++)
    {
        printf("P%d: ", i + 1);
        scanf("%d", &bt[i]);
    }

    // First process does not wait
    wt[0] = 0;

    // Each process waits for all the ones before it
    for (i = 1; i < n; i++)
        wt[i] = wt[i - 1] + bt[i - 1];

    for (i = 0; i < n; i++)
    {
        tat[i] = wt[i] + bt[i];
        total_wt += wt[i];
        total_tat += tat[i];
    }

    printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
    for (i = 0; i < n; i++)
        printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, bt[i], wt[i], tat[i]);

    printf("\nAverage Waiting Time    = %.2f\n", total_wt / n);
    printf("Average Turnaround Time = %.2f\n", total_tat / n);

    return 0;
}

Output

Input typed: 3 ⏎ 5 ⏎ 3 ⏎ 8

Enter number of processes: 3
Enter burst time for each process:
P1: 5
P2: 3
P3: 8

Process Burst Time      Waiting Time    Turnaround Time
P1      5               0               5
P2      3               5               8
P3      8               8               16

Average Waiting Time    = 4.33
Average Turnaround Time = 9.67

Viva: which commands are used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Viva: what does each line do?

  1. int main()

    This line defines a function. main() is where the program starts running.

  2. int n, i;

    Declares the variables used below. n is the number of elements (or processes).

  3. int bt[20], wt[20], tat[20];

    Declares the variables used below. bt holds each process's burst time (CPU time needed). wt holds each process's waiting time.

  4. float total_wt = 0, total_tat = 0;

    Declares the variables used below. total_wt sums waiting times for the average. total_tat sums turnaround times for the average.

  5. printf("Enter number of processes: ");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  6. scanf("%d", &n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  7. printf("Enter burst time for each process:\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  8. for (i = 0; i < n; i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  9. printf("P%d: ", i + 1);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  10. scanf("%d", &bt[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &. bt holds each process's burst time (CPU time needed).

  11. wt[0] = 0;

    wt holds each process's waiting time.

  12. for (i = 1; i < n; i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  13. wt[i] = wt[i - 1] + bt[i - 1];

    wt holds each process's waiting time. bt holds each process's burst time (CPU time needed).

  14. tat[i] = wt[i] + bt[i];

    tat is the turnaround time = completion − arrival. wt holds each process's waiting time. bt holds each process's burst time (CPU time needed).

  15. total_wt += wt[i];

    total_wt sums waiting times for the average. wt holds each process's waiting time.

  16. total_tat += tat[i];

    total_tat sums turnaround times for the average. tat is the turnaround time = completion − arrival.

  17. printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  18. printf("P%d\t%d\t\t%d\t\t%d\n", i + 1, bt[i], wt[i], tat[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). bt holds each process's burst time (CPU time needed).

  19. printf("\nAverage Waiting Time    = %.2f\n", total_wt / n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). total_wt sums waiting times for the average.

  20. printf("Average Turnaround Time = %.2f\n", total_tat / n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). total_tat sums turnaround times for the average.

  21. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. FCFS runs processes in order of…

A. Arrival (first come, first served). It is non-preemptive and uses a FIFO queue.

Q. With all arrivals at 0, a process's waiting time is…

A. The sum of the bursts before it. That is exactly wt[i] = wt[i-1] + bt[i-1].

Q. FCFS's main drawback is…

A. The convoy effect: short jobs wait behind a long one. One long burst at the front raises everyone's waiting time.

Program 16

Priority scheduling (C)

Write a program in c to implement the priority bases scheduling algorithm

Run it

Algorithm

1. Start
2. Read burst time and priority for each process
3. Sort by priority (smaller number = higher priority), swapping bt and pid too
4. Compute wt and tat as in FCFS and print the averages
5. Stop

Program

// A lower number means a higher priority

#include <stdio.h>

int main()
{
    int n, i, j, temp;
    int p[20], bt[20], pr[20], wt[20], tat[20];
    float total_wt = 0, total_tat = 0;

    printf("Enter number of processes: ");
    scanf("%d", &n);

    printf("Enter burst time and priority for each process:\n");
    for (i = 0; i < n; i++)
    {
        printf("P%d: ", i + 1);
        scanf("%d %d", &bt[i], &pr[i]);
        p[i] = i + 1;
    }

    // Sort processes by priority (selection sort)
    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (pr[j] < pr[i])
            {
                temp = pr[i]; pr[i] = pr[j]; pr[j] = temp;
                temp = bt[i]; bt[i] = bt[j]; bt[j] = temp;
                temp = p[i];  p[i] = p[j];   p[j] = temp;
            }
        }
    }

    wt[0] = 0;
    for (i = 1; i < n; i++)
        wt[i] = wt[i - 1] + bt[i - 1];

    for (i = 0; i < n; i++)
    {
        tat[i] = wt[i] + bt[i];
        total_wt += wt[i];
        total_tat += tat[i];
    }

    printf("\nProcess\tPriority\tBurst Time\tWaiting Time\tTurnaround Time\n");
    for (i = 0; i < n; i++)
        printf("P%d\t%d\t\t%d\t\t%d\t\t%d\n", p[i], pr[i], bt[i], wt[i], tat[i]);

    printf("\nAverage Waiting Time    = %.2f\n", total_wt / n);
    printf("Average Turnaround Time = %.2f\n", total_tat / n);

    return 0;
}

Output

Input typed: 4 ⏎ 10 3 ⏎ 1 1 ⏎ 2 4 ⏎ 5 2

Enter number of processes: 4
Enter burst time and priority for each process:
P1: 10 3
P2: 1 1
P3: 2 4
P4: 5 2

Process Priority        Burst Time      Waiting Time    Turnaround Time
P2      1               1               0               1
P4      2               5               1               6
P1      3               10              6               16
P3      4               2               16              18

Average Waiting Time    = 5.75
Average Turnaround Time = 10.25

Viva: which commands are used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Viva: what does each line do?

  1. int main()

    This line defines a function. main() is where the program starts running.

  2. int n, i, j, temp;

    Declares the variables used below. n is the number of elements (or processes). temp holds one value while two are swapped.

  3. int p[20], bt[20], pr[20], wt[20], tat[20];

    Declares the variables used below. bt holds each process's burst time (CPU time needed). pr holds each process's priority.

  4. float total_wt = 0, total_tat = 0;

    Declares the variables used below. total_wt sums waiting times for the average. total_tat sums turnaround times for the average.

  5. printf("Enter number of processes: ");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  6. scanf("%d", &n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  7. printf("Enter burst time and priority for each process:\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  8. for (i = 0; i < n; i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  9. printf("P%d: ", i + 1);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  10. scanf("%d %d", &bt[i], &pr[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &. bt holds each process's burst time (CPU time needed).

  11. p[i] = i + 1;

    i is the loop counter.

  12. for (i = 0; i < n - 1; i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  13. for (j = i + 1; j < n; j++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  14. if (pr[j] < pr[i])

    This line is a decision. if runs the block only when the condition is true. pr holds each process's priority.

  15. temp = pr[i]; pr[i] = pr[j]; pr[j] = temp;

    Part of a swap: temp holds one value while the two are exchanged. temp holds one value while two are swapped. pr holds each process's priority.

  16. temp = bt[i]; bt[i] = bt[j]; bt[j] = temp;

    Part of a swap: temp holds one value while the two are exchanged. temp holds one value while two are swapped. bt holds each process's burst time (CPU time needed).

  17. temp = p[i];  p[i] = p[j];   p[j] = temp;

    Part of a swap: temp holds one value while the two are exchanged. temp holds one value while two are swapped.

  18. wt[0] = 0;

    wt holds each process's waiting time.

  19. for (i = 1; i < n; i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  20. wt[i] = wt[i - 1] + bt[i - 1];

    wt holds each process's waiting time. bt holds each process's burst time (CPU time needed).

  21. tat[i] = wt[i] + bt[i];

    tat is the turnaround time = completion − arrival. wt holds each process's waiting time. bt holds each process's burst time (CPU time needed).

  22. total_wt += wt[i];

    total_wt sums waiting times for the average. wt holds each process's waiting time.

  23. total_tat += tat[i];

    total_tat sums turnaround times for the average. tat is the turnaround time = completion − arrival.

  24. printf("\nProcess\tPriority\tBurst Time\tWaiting Time\tTurnaround Time\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  25. printf("P%d\t%d\t\t%d\t\t%d\t\t%d\n", p[i], pr[i], bt[i], wt[i], tat[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). pr holds each process's priority.

  26. printf("\nAverage Waiting Time    = %.2f\n", total_wt / n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). total_wt sums waiting times for the average.

  27. printf("Average Turnaround Time = %.2f\n", total_tat / n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). total_tat sums turnaround times for the average.

  28. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. The main problem with priority scheduling is…

A. Starvation of low-priority processes. The fix is aging: slowly raise a waiting process's priority.

Q. Non-preemptive means…

A. A running process keeps the CPU until it finishes. Preemptive priority would switch as soon as a higher-priority job arrives.

Program 31

Round Robin scheduling

Write A Program in shell script to implement the round robin scheduling Algorithm

Run it

Algorithm

1. Start
2. Read n, each burst time into bt[i] (copy into rem[i]), and the time quantum q
3. Loop while processes are left: each one with rem[i] > 0 runs min(q, rem[i]); when rem[i] hits 0, ct[i] = time
4. Tat = ct (all arrive at 0), wt = tat − bt; print the Gantt chart, the table and both averages
5. Stop

Program

#!/bin/bash

echo "Enter number of processes:"
read n

echo "Enter burst time of each process:"
for (( i = 0; i < n; i++ ))
do
    read bt[i]
    rem[i]=${bt[i]}
done

echo "Enter time quantum:"
read q

time=0
left=$n
gantt="0"

# Keep cycling through the ready queue until every process is done
while (( left > 0 ))
do
    for (( i = 0; i < n; i++ ))
    do
        if (( rem[i] > 0 ))
        then
            if (( rem[i] > q ))
            then
                time=$((time + q))
                rem[i]=$((rem[i] - q))
            else
                time=$((time + rem[i]))
                rem[i]=0
                ct[i]=$time
                left=$((left - 1))
            fi
            gantt="$gantt | P$((i + 1)) | $time"
        fi
    done
done

echo
echo "Gantt chart: $gantt"
echo

total_wt=0
total_tat=0
printf "%-10s%-8s%-8s%s\n" "Process" "BT" "WT" "TAT"
for (( i = 0; i < n; i++ ))
do
    tat[i]=${ct[i]}
    wt[i]=$((tat[i] - bt[i]))
    total_wt=$((total_wt + wt[i]))
    total_tat=$((total_tat + tat[i]))
    printf "%-10s%-8s%-8s%s\n" "P$((i + 1))" "${bt[i]}" "${wt[i]}" "${tat[i]}"
done

echo
echo "Average Waiting Time    = $(echo "scale=2; $total_wt / $n" | bc)"
echo "Average Turnaround Time = $(echo "scale=2; $total_tat / $n" | bc)"

Output

Input typed: 3 ⏎ 5 ⏎ 3 ⏎ 8 ⏎ 4

Enter number of processes:
3
Enter burst time of each process:
5
3
8
Enter time quantum:
4

Gantt chart: 0 | P1 | 4 | P2 | 7 | P3 | 11 | P1 | 12 | P3 | 16

Process   BT      WT      TAT
P1        5       7       12
P2        3       4       7
P3        8       8       16

Average Waiting Time    = 6.33
Average Turnaround Time = 11.66

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range. while repeats as long as the condition is true. printf prints with a format, like C's printf.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter number of processes:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. echo "Enter burst time of each process:"

    This line prints to the terminal. echo prints text to the terminal.

  5. for (( i = 0; i < n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  6. read bt[i]

    This line takes keyboard input. read waits for keyboard input and stores it in bt[i].

  7. echo "Enter time quantum:"

    This line prints to the terminal. echo prints text to the terminal.

  8. read q

    This line takes keyboard input. read waits for keyboard input and stores it in q.

  9. time=0

    Sets the variable time (no spaces around = in bash).

  10. left=$n

    Sets the variable left (no spaces around = in bash).

  11. gantt="0"

    Sets the variable gantt (no spaces around = in bash).

  12. while (( left > 0 ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. while repeats as long as the condition is true.

  13. if (( rem[i] > 0 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  14. if (( rem[i] > q ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  15. time=$((time + q))

    $(( … )) does integer arithmetic.

  16. rem[i]=$((rem[i] - q))

    $(( … )) does integer arithmetic.

  17. time=$((time + rem[i]))

    $(( … )) does integer arithmetic.

  18. left=$((left - 1))

    $(( … )) does integer arithmetic.

  19. gantt="$gantt | P$((i + 1)) | $time"

    $(( … )) does integer arithmetic.

  20. echo

    This line prints to the terminal. echo prints text to the terminal.

  21. echo "Gantt chart: $gantt"

    This line prints to the terminal. echo prints text to the terminal.

  22. total_wt=0

    Sets the variable total_wt (no spaces around = in bash).

  23. total_tat=0

    Sets the variable total_tat (no spaces around = in bash).

  24. printf "%-10s%-8s%-8s%s\n" "Process" "BT" "WT" "TAT"

    printf prints with a format, like C's printf.

  25. wt[i]=$((tat[i] - bt[i]))

    $(( … )) does integer arithmetic.

  26. total_wt=$((total_wt + wt[i]))

    $(( … )) does integer arithmetic.

  27. total_tat=$((total_tat + tat[i]))

    $(( … )) does integer arithmetic.

  28. printf "%-10s%-8s%-8s%s\n" "P$((i + 1))" "${bt[i]}" "${wt[i]}" "${tat[i]}"

    $(( … )) does integer arithmetic. printf prints with a format, like C's printf.

  29. echo "Average Waiting Time    = $(echo "scale=2; $total_wt / $n" | bc)"

    This line prints to the terminal. $( … ) runs a command and puts its output here (command substitution). bc is the command-line calculator; bash only does integers, so bc handles decimals.

  30. echo "Average Turnaround Time = $(echo "scale=2; $total_tat / $n" | bc)"

    This line prints to the terminal. $( … ) runs a command and puts its output here (command substitution). bc is the command-line calculator; bash only does integers, so bc handles decimals.

Viva: concepts

Q. Round Robin is…

A. Preemptive: each process runs for at most one time quantum. When the quantum runs out, the process goes to the back of the ready queue.

Q. With bursts 5, 3, 8 and q = 4, the order of slices is…

A. P1 P2 P3 P1 P3. P1 runs 4 (1 left), P2 finishes in 3, P3 runs 4 (4 left), then P1 finishes, then P3.

Q. If the time quantum is very large, Round Robin becomes…

A. FCFS. Every process finishes inside its first slice, so it is first come, first served.

Q. A very small quantum causes…

A. Too many context switches (overhead). Typical quanta are 10–100 ms, much larger than a context switch.

Q. Why does the script keep a separate rem[] array?

A. bt[] must stay unchanged to compute WT = TAT − BT at the end. rem[i] is the remaining burst; it counts down to 0.

Deadlock & memory

Program 32

Banker's algorithm (deadlock avoidance)

Write shell script for Bankers Algorithm.

Run it

Algorithm

1. Start
2. Read n, m, the Allocation and Max matrices (row by row) and Available
3. Need[i][j] = Max[i][j] − Allocation[i][j]; Work = Available, Finish[i] = 0
4. Repeat: find a process with Finish = 0 and Need ≤ Work; add its Allocation to Work, mark it finished, append it to the safe sequence. All finished → SAFE, else UNSAFE
5. Stop

Program

#!/bin/bash

echo "Enter number of processes:"
read n
echo "Enter number of resource types:"
read m

# 2D matrices are stored in 1D arrays: row i, column j is at index i * m + j
echo "Enter Allocation matrix (one row per process):"
for (( i = 0; i < n; i++ ))
do
    read line
    j=0
    for x in $line
    do
        alloc[i * m + j]=$x
        j=$((j + 1))
    done
done

echo "Enter Max matrix (one row per process):"
for (( i = 0; i < n; i++ ))
do
    read line
    j=0
    for x in $line
    do
        max[i * m + j]=$x
        j=$((j + 1))
    done
done

echo "Enter Available resources:"
read line
j=0
for x in $line
do
    work[j]=$x
    j=$((j + 1))
done

# Need = Max - Allocation
echo
echo "Need matrix:"
for (( i = 0; i < n; i++ ))
do
    row=""
    for (( j = 0; j < m; j++ ))
    do
        need[i * m + j]=$((max[i * m + j] - alloc[i * m + j]))
        row="$row ${need[i * m + j]}"
    done
    echo "P$i:$row"
    finish[i]=0
done

# Safety algorithm
seq=""
count=0
found=1
while (( count < n && found == 1 ))
do
    found=0
    for (( i = 0; i < n; i++ ))
    do
        if (( finish[i] == 0 ))
        then
            ok=1
            for (( j = 0; j < m; j++ ))
            do
                if (( need[i * m + j] > work[j] ))
                then
                    ok=0
                fi
            done

            if (( ok == 1 ))
            then
                # Process i can finish, so it gives back what it holds
                for (( j = 0; j < m; j++ ))
                do
                    work[j]=$((work[j] + alloc[i * m + j]))
                done
                finish[i]=1
                seq="$seq P$i"
                count=$((count + 1))
                found=1
            fi
        fi
    done
done

echo
if (( count == n ))
then
    echo "The system is in a SAFE state."
    echo "Safe sequence:$seq"
else
    echo "The system is in an UNSAFE state (deadlock possible)."
fi

Output

Input typed: 5 ⏎ 3 ⏎ 0 1 0 ⏎ 2 0 0 ⏎ 3 0 2 ⏎ 2 1 1 ⏎ 0 0 2 ⏎ 7 5 3 ⏎ 3 2 2 ⏎ 9 0 2 ⏎ 2 2 2 ⏎ 4 3 3 ⏎ 3 3 2

Enter number of processes:
5
Enter number of resource types:
3
Enter Allocation matrix (one row per process):
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
Enter Max matrix (one row per process):
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
Enter Available resources:
3 3 2

Need matrix:
P0: 7 4 3
P1: 1 2 2
P2: 6 0 0
P3: 0 1 1
P4: 4 3 1

The system is in a SAFE state.
Safe sequence: P1 P3 P4 P0 P2

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range. while repeats as long as the condition is true.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter number of processes:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read n

    This line takes keyboard input. read waits for keyboard input and stores it in n.

  4. echo "Enter number of resource types:"

    This line prints to the terminal. echo prints text to the terminal.

  5. read m

    This line takes keyboard input. read waits for keyboard input and stores it in m.

  6. echo "Enter Allocation matrix (one row per process):"

    This line prints to the terminal. echo prints text to the terminal.

  7. for (( i = 0; i < n; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  8. read line

    This line takes keyboard input. read waits for keyboard input and stores it in line.

  9. j=0

    Sets the variable j (no spaces around = in bash).

  10. for x in $line

    This line starts a loop. for loops over a list or a counted range. in introduces the list a for loop runs over, or the value case matches.

  11. j=$((j + 1))

    $(( … )) does integer arithmetic.

  12. echo "Enter Max matrix (one row per process):"

    This line prints to the terminal. echo prints text to the terminal.

  13. echo "Enter Available resources:"

    This line prints to the terminal. echo prints text to the terminal.

  14. echo

    This line prints to the terminal. echo prints text to the terminal.

  15. echo "Need matrix:"

    This line prints to the terminal. echo prints text to the terminal.

  16. row=""

    Sets the variable row (no spaces around = in bash).

  17. for (( j = 0; j < m; j++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  18. need[i * m + j]=$((max[i * m + j] - alloc[i * m + j]))

    $(( … )) does integer arithmetic.

  19. row="$row ${need[i * m + j]}"

    Sets the variable row (no spaces around = in bash).

  20. echo "P$i:$row"

    This line prints to the terminal. echo prints text to the terminal.

  21. seq=""

    Sets the variable seq (no spaces around = in bash).

  22. count=0

    Sets the variable count (no spaces around = in bash).

  23. found=1

    Sets the variable found (no spaces around = in bash).

  24. while (( count < n && found == 1 ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. while repeats as long as the condition is true.

  25. found=0

    Sets the variable found (no spaces around = in bash).

  26. if (( finish[i] == 0 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  27. ok=1

    Sets the variable ok (no spaces around = in bash).

  28. if (( need[i * m + j] > work[j] ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  29. ok=0

    Sets the variable ok (no spaces around = in bash).

  30. if (( ok == 1 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  31. work[j]=$((work[j] + alloc[i * m + j]))

    $(( … )) does integer arithmetic.

  32. seq="$seq P$i"

    Sets the variable seq (no spaces around = in bash).

  33. count=$((count + 1))

    $(( … )) does integer arithmetic.

  34. if (( count == n ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  35. echo "The system is in a SAFE state."

    This line prints to the terminal. echo prints text to the terminal.

  36. echo "Safe sequence:$seq"

    This line prints to the terminal. echo prints text to the terminal.

  37. echo "The system is in an UNSAFE state (deadlock possible)."

    This line prints to the terminal. echo prints text to the terminal.

Viva: concepts

Q. The Banker's algorithm is used for deadlock…

A. Avoidance. It refuses any request that would leave the system in an unsafe state.

Q. Need = ?

A. Max − Allocation. What the process may still ask for.

Q. A process can run in the safety check when…

A. Its Need ≤ Work for every resource. Then it can finish and return all it holds: Work = Work + Allocation.

Q. A safe state means…

A. There is an order in which every process can finish. Unsafe does not always mean deadlock, but deadlock is possible.

Q. Why are the matrices stored as alloc[i * m + j]?

A. Bash has only 1D arrays, so row i, column j is flattened. With m = 3, row 2 column 1 is index 7.

Program 33

First Fit, Best Fit, Worst Fit

Write shell script for the following memory management methods, First Fit, Best Fit, and Worst fit.

Run it

Algorithm

1. Start
2. Read the block sizes into block[] and the process sizes into proc[]
3. Allocate() copies block[] to hole[]; for each process scan every block that is big enough: First Fit takes the first, Best Fit the smallest, Worst Fit the largest
4. Subtract the process size from that block (hole[pick] −= size), print the block and what is left, or 'Not allocated'
5. Stop

Program

#!/bin/bash

echo "Enter number of memory blocks:"
read nb
echo "Enter size of each block:"
for (( j = 0; j < nb; j++ ))
do
    read block[j]
done

echo "Enter number of processes:"
read np
echo "Enter size of each process:"
for (( i = 0; i < np; i++ ))
do
    read proc[i]
done

# $1 is the method name: First Fit, Best Fit or Worst Fit
allocate()
{
    # Every method starts again with all the blocks free
    for (( j = 0; j < nb; j++ ))
    do
        hole[j]=${block[j]}
    done

    echo
    echo "---------- $1 ----------"
    printf "%-10s%-8s%-8s%s\n" "Process" "Size" "Block" "Left"

    for (( i = 0; i < np; i++ ))
    do
        pick=-1
        for (( j = 0; j < nb; j++ ))
        do
            if (( hole[j] >= proc[i] ))
            then
                if (( pick == -1 ))
                then
                    pick=$j
                    # First Fit stops at the first block that is big enough
                    if [ "$1" = "First Fit" ]
                    then
                        break
                    fi
                elif [ "$1" = "Best Fit" ] && (( hole[j] < hole[pick] ))
                then
                    pick=$j    # smallest block that fits
                elif [ "$1" = "Worst Fit" ] && (( hole[j] > hole[pick] ))
                then
                    pick=$j    # largest block that fits
                fi
            fi
        done

        if (( pick == -1 ))
        then
            printf "%-10s%-8s%s\n" "P$((i + 1))" "${proc[i]}" "Not allocated"
        else
            hole[pick]=$((hole[pick] - proc[i]))
            printf "%-10s%-8s%-8s%s\n" "P$((i + 1))" "${proc[i]}" "B$((pick + 1))" "${hole[pick]}"
        fi
    done
}

allocate "First Fit"
allocate "Best Fit"
allocate "Worst Fit"

Output

Input typed: 5 ⏎ 100 ⏎ 500 ⏎ 200 ⏎ 300 ⏎ 600 ⏎ 4 ⏎ 212 ⏎ 417 ⏎ 112 ⏎ 426

Enter number of memory blocks:
5
Enter size of each block:
100
500
200
300
600
Enter number of processes:
4
Enter size of each process:
212
417
112
426

---------- First Fit ----------
Process   Size    Block   Left
P1        212     B2      288
P2        417     B5      183
P3        112     B2      176
P4        426     Not allocated

---------- Best Fit ----------
Process   Size    Block   Left
P1        212     B4      88
P2        417     B2      83
P3        112     B3      88
P4        426     B5      174

---------- Worst Fit ----------
Process   Size    Block   Left
P1        212     B5      388
P2        417     B2      83
P3        112     B5      276
P4        426     Not allocated

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. read waits for a line of keyboard input and stores it in a variable. for loops over a list or a counted range. printf prints with a format, like C's printf. break leaves the loop immediately.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. echo "Enter number of memory blocks:"

    This line prints to the terminal. echo prints text to the terminal.

  3. read nb

    This line takes keyboard input. read waits for keyboard input and stores it in nb.

  4. echo "Enter size of each block:"

    This line prints to the terminal. echo prints text to the terminal.

  5. for (( j = 0; j < nb; j++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  6. read block[j]

    This line takes keyboard input. read waits for keyboard input and stores it in block[j].

  7. echo "Enter number of processes:"

    This line prints to the terminal. echo prints text to the terminal.

  8. read np

    This line takes keyboard input. read waits for keyboard input and stores it in np.

  9. echo "Enter size of each process:"

    This line prints to the terminal. echo prints text to the terminal.

  10. for (( i = 0; i < np; i++ ))

    This line starts a loop. (( … )) is an arithmetic test or C-style loop. for loops over a list or a counted range.

  11. read proc[i]

    This line takes keyboard input. read waits for keyboard input and stores it in proc[i].

  12. echo

    This line prints to the terminal. echo prints text to the terminal.

  13. echo "---------- $1 ----------"

    This line prints to the terminal. $1 is the first argument passed to the function or script. echo prints text to the terminal.

  14. printf "%-10s%-8s%-8s%s\n" "Process" "Size" "Block" "Left"

    printf prints with a format, like C's printf.

  15. pick=-1

    Sets the variable pick (no spaces around = in bash).

  16. if (( hole[j] >= proc[i] ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  17. if (( pick == -1 ))

    This line is a condition test. (( … )) is an arithmetic test or C-style loop.

  18. pick=$j

    Sets the variable pick (no spaces around = in bash).

  19. if [ "$1" = "First Fit" ]

    This line is a condition test. [ … ] is a test; it's true or false, used by if and while. $1 is the first argument passed to the function or script.

  20. break

    break leaves the loop immediately.

  21. elif [ "$1" = "Best Fit" ] && (( hole[j] < hole[pick] ))

    This line is a condition test. [ … ] is a test; it's true or false, used by if and while. $1 is the first argument passed to the function or script.

  22. pick=$j    # smallest block that fits

    Sets the variable pick (no spaces around = in bash).

  23. elif [ "$1" = "Worst Fit" ] && (( hole[j] > hole[pick] ))

    This line is a condition test. [ … ] is a test; it's true or false, used by if and while. $1 is the first argument passed to the function or script.

  24. pick=$j    # largest block that fits

    Sets the variable pick (no spaces around = in bash).

  25. printf "%-10s%-8s%s\n" "P$((i + 1))" "${proc[i]}" "Not allocated"

    $(( … )) does integer arithmetic. printf prints with a format, like C's printf.

  26. hole[pick]=$((hole[pick] - proc[i]))

    $(( … )) does integer arithmetic.

  27. printf "%-10s%-8s%-8s%s\n" "P$((i + 1))" "${proc[i]}" "B$((pick + 1))" "${hole[pick]}"

    $(( … )) does integer arithmetic. printf prints with a format, like C's printf.

Viva: concepts

Q. Best Fit chooses…

A. The smallest free block that is big enough. It leaves the smallest leftover hole.

Q. Worst Fit chooses…

A. The largest free block. It leaves a big leftover that may still be useful.

Q. Which one is usually fastest?

A. First Fit: it stops at the first block that fits. Best and Worst Fit must scan every block.

Q. These methods suffer from…

A. External fragmentation. Free memory is split into small holes; compaction or paging fixes it.

Q. Blocks 100 500 200 300 600, processes 212 417 112 426: which method places all four?

A. Best Fit. First and Worst Fit leave 426 Not allocated.

Linux commands

Program 30

Linux commands

Linux commands such as mkdir,grep,sed,cal,cat,cd,xclock,oclock,>>(append),ls etc

Run it

Algorithm

1. Start
2. Mkdir, cd, ls: make and move around folders
3. > writes, >> appends; cat shows a file
4. Grep searches, sed replaces, cal shows a calendar; xclock / oclock need X11
5. Stop

Program

#!/bin/bash
# mkdir, cd, ls, cat, >, >> (append), grep, sed, cal, xclock, oclock
# Everything runs inside a throwaway folder, so nothing else is touched.

work=$(mktemp -d)

echo "== mkdir: create a directory =="
mkdir "$work/demo"
echo "Created demo/"

echo
echo "== cd: change directory =="
cd "$work/demo"
echo "Now in: $(basename "$PWD")"

echo
echo "== > (write) and >> (append) =="
echo "apple" > fruits.txt
echo "banana" >> fruits.txt
echo "cherry" >> fruits.txt
echo "mango" >> fruits.txt
echo "Wrote 1 line with > and appended 3 with >>"

echo
echo "== ls: list files =="
ls

echo
echo "== cat: show file contents =="
cat fruits.txt

echo
echo "== grep: search for lines containing 'an' =="
grep "an" fruits.txt

echo
echo "== sed: replace 'apple' with 'grape' =="
sed 's/apple/grape/' fruits.txt

echo
echo "== cal: calendar for July 2026 =="
cal 7 2026

echo
echo "== xclock / oclock: graphical clocks (need X11) =="
for clock in xclock oclock
do
    if command -v $clock > /dev/null 2>&1 && [ -n "$DISPLAY" ]
    then
        echo "Starting $clock (close its window to continue)"
        $clock
    else
        echo "$clock: not available here (install x11-apps and run inside X11)"
    fi
done

cd /
rm -rf "$work"

Output

== mkdir: create a directory ==
Created demo/

== cd: change directory ==
Now in: demo

== > (write) and >> (append) ==
Wrote 1 line with > and appended 3 with >>

== ls: list files ==
fruits.txt

== cat: show file contents ==
apple
banana
cherry
mango

== grep: search for lines containing 'an' ==
banana
mango

== sed: replace 'apple' with 'grape' ==
grape
banana
cherry
mango

== cal: calendar for July 2026 ==
     July 2026
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31


== xclock / oclock: graphical clocks (need X11) ==
Starting xclock (close its window to continue)

  [ an xclock window opens ]
  +--------- xclock ---------+
  |            12            |
  |      11    |     1       |
  |   10       |        2    |
  |            |             |
  |  9         o-------  3   |
  |                          |
  |   8                 4    |
  |      7           5       |
  |            6             |
  +--------------------------+

Starting oclock (close its window to continue)

  [ an oclock window opens ]
         .-""""""""-.
       .'     |      '.
      /       |        \
     ;        |         ;
     |        o------   |
     ;                  ;
      \                /
       '.            .'
         '-........-'

(On a machine without X11 the script prints instead:)
xclock: not available here (install x11-apps and run inside X11)
oclock: not available here (install x11-apps and run inside X11)

Viva: which commands are used and why

Q. Why #!/bin/bash on the first line?

A. It's the shebang: it tells the system to run the file with bash. Run it with bash file.sh or ./file.sh after chmod +x.

Q. Which commands does this script use, and for what?

A. echo prints text to the terminal. mkdir creates a directory. cd changes the current directory. ls lists the files in a directory. cat prints a file's contents. grep prints lines that match a pattern. sed edits text as a stream (e.g. find and replace). cal prints a calendar. for loops over a list or a counted range. rm deletes files.

Viva: what does each line do?

  1. #!/bin/bash

    The shebang: tells the system to run this file with bash.

  2. work=$(mktemp -d)

    $( … ) runs a command and puts its output here (command substitution). -d is true when the path is a directory.

  3. echo "== mkdir: create a directory =="

    This line prints to the terminal. echo prints text to the terminal.

  4. mkdir "$work/demo"

    mkdir creates a directory.

  5. echo "Created demo/"

    This line prints to the terminal. echo prints text to the terminal.

  6. echo

    This line prints to the terminal. echo prints text to the terminal.

  7. echo "== cd: change directory =="

    This line prints to the terminal. echo prints text to the terminal.

  8. cd "$work/demo"

    cd changes the current directory.

  9. echo "Now in: $(basename "$PWD")"

    This line prints to the terminal. $( … ) runs a command and puts its output here (command substitution). echo prints text to the terminal.

  10. echo "== > (write) and >> (append) =="

    This line prints to the terminal. echo prints text to the terminal.

  11. echo "apple" > fruits.txt

    This line prints to the terminal. echo prints text to the terminal.

  12. echo "banana" >> fruits.txt

    This line prints to the terminal. echo prints text to the terminal.

  13. echo "cherry" >> fruits.txt

    This line prints to the terminal. echo prints text to the terminal.

  14. echo "mango" >> fruits.txt

    This line prints to the terminal. echo prints text to the terminal.

  15. echo "Wrote 1 line with > and appended 3 with >>"

    This line prints to the terminal. echo prints text to the terminal.

  16. echo "== ls: list files =="

    This line prints to the terminal. echo prints text to the terminal.

  17. ls

    ls lists the files in a directory.

  18. echo "== cat: show file contents =="

    This line prints to the terminal. echo prints text to the terminal.

  19. cat fruits.txt

    cat prints a file's contents.

  20. echo "== grep: search for lines containing 'an' =="

    This line prints to the terminal. echo prints text to the terminal.

  21. grep "an" fruits.txt

    grep prints lines that match a pattern.

  22. echo "== sed: replace 'apple' with 'grape' =="

    This line prints to the terminal. echo prints text to the terminal.

  23. sed 's/apple/grape/' fruits.txt

    sed edits text as a stream (e.g. find and replace).

  24. echo "== cal: calendar for July 2026 =="

    This line prints to the terminal. echo prints text to the terminal.

  25. cal 7 2026

    cal prints a calendar.

  26. echo "== xclock / oclock: graphical clocks (need X11) =="

    This line prints to the terminal. echo prints text to the terminal.

  27. for clock in xclock oclock

    This line starts a loop. for loops over a list or a counted range. in introduces the list a for loop runs over, or the value case matches.

  28. if command -v $clock > /dev/null 2>&1 && [ -n "$DISPLAY" ]

    This line is a condition test. [ … ] is a test; it's true or false, used by if and while. -n is true when a string is not empty.

  29. echo "Starting $clock (close its window to continue)"

    This line prints to the terminal. echo prints text to the terminal.

  30. echo "$clock: not available here (install x11-apps and run inside X11)"

    This line prints to the terminal. echo prints text to the terminal.

  31. cd /

    cd changes the current directory.

  32. rm -rf "$work"

    rm deletes files.

Viva: concepts

Q. What is the difference between > and >>?

A. > overwrites the file, >> appends to it. echo hi >> notes.txt adds a line at the end.

Q. grep -i 'an' file…

A. Finds lines containing 'an', ignoring case. -v inverts, -n shows line numbers, -c counts.

Q. sed 's/apple/grape/g' does…

A. Replace every 'apple' with 'grape' on each line. Without g, only the first match on each line is replaced.

Theory: formulas and commands

Read & print

echo "Enter a number:"
read n
echo "You typed $n"
read a b        # two values on one line
read -p "Name: " name

Arithmetic

sum=$((a + b))
rem=$((n % 10))
let c=a*b
x=$(expr $a + $b)
# decimals need bc:
area=$(echo "scale=2; 3.14 * $r * $r" | bc)

if / elif / else

if [ $n -gt 0 ]
then
    echo "positive"
elif [ $n -eq 0 ]
then
    echo "zero"
else
    echo "negative"
fi

Loops

for ((i = 1; i <= 10; i++))
do
    echo $i
done

while [ $n -gt 0 ]
do
    n=$((n - 1))
done

for f in a b c; do echo $f; done

case menu

case $choice in
    1) echo "one" ;;
    2) echo "two" ;;
    *) echo "invalid" ;;
esac

Functions & arrays

square() {
    local x=$1
    echo $((x * x))
}
res=$(square 5)

arr=(10 20 30)
echo ${arr[0]} ${arr[@]} ${#arr[@]}

Scheduling, deadlock and memory formulas

FormulaMeaning
TAT = CT − ATturnaround = completion − arrival
WT = TAT − BTwaiting = turnaround − burst
RT = first run − ATresponse time
FCFS (AT = 0)wt[i] = wt[i−1] + bt[i−1]
Averagesum of WT (or TAT) ÷ n
Round Robinrun min(q, remaining); unfinished → back of queue
Banker's: NeedNeed = Max − Allocation
Banker's: safeNeed ≤ Work → Work = Work + Allocation
First / Best / Worst Fitfirst big-enough / smallest that fits / largest block

Test operators inside [ ]

OperatorMeaning
-eq / -neequal / not equal
-gt / -gegreater than / greater or equal
-lt / -leless than / less or equal
= / != (strings)string equal / not equal
-z $s / -n $sstring is empty / not empty
-f file / -d dirfile exists / directory exists
&& / ||and / or between tests

Common Linux commands

CommandWhat it does
pwd, ls -l, cd dir, cd ..where am I, list, move around
mkdir d, rmdir d, rm -r dmake / remove folders
touch f, cp a b, mv a b, rm fcreate, copy, move or rename, delete
cat f, head -n 5 f, tail f, wc -l fshow, first / last lines, count lines
echo hi > f, echo hi >> foverwrite, append
grep -i 'x' f, grep -v, grep -csearch (ignore case), invert, count
sed 's/old/new/g' ffind and replace on every line
sort f | uniq, cut -d, -f1sort, de-duplicate, pick columns
chmod +x s.sh, chmod 755 fpermissions (r=4 w=2 x=1)
ps, top, kill PID, &processes, stop one, run in background
cal 7 2026, date, whoami, uname -acalendar, date, user, system info
xclock, oclockgraphical clocks (need X11)

Subject viva

OS basics

Q. What is an operating system?

A. System software that manages hardware (CPU, memory, devices, files) and gives programs services and a user interface. Examples: Linux, Windows, macOS.

Q. Kernel vs shell?

A. The kernel is the core of the OS that talks to the hardware and manages processes, memory and devices. The shell is a command interpreter that takes user commands and asks the kernel to run them.

Q. Types of operating systems?

A. Batch, multiprogramming, time-sharing (multitasking), real-time (hard or soft), distributed, network, and mobile/embedded.

Q. What is a system call?

A. The interface a program uses to request a kernel service, e.g. fork(), exec(), read(), write(), open(). It switches from user mode to kernel mode.

Processes

Q. Program vs process vs thread?

A. A program is a passive file on disk. A process is a running program with its own memory and PCB. A thread is a lightweight unit of execution inside a process that shares the process's memory.

Q. What does a PCB contain?

A. The Process Control Block holds the PID, process state, program counter, CPU registers, scheduling priority, memory-management info, open files and accounting data.

Q. What are the process states?

A. New → Ready → Running → Terminated, with Waiting (blocked) for I/O. A running process returns to Ready when preempted.

Q. What is a context switch?

A. Saving the state of the running process into its PCB and loading another process's state. It is pure overhead: no useful work happens during it.

Scheduling

Q. Preemptive vs non-preemptive scheduling?

A. Non-preemptive: a process keeps the CPU until it finishes or blocks (FCFS, SJF). Preemptive: the OS can take the CPU away (Round Robin, SRTF, preemptive priority).

Q. Define turnaround time and waiting time.

A. TAT = Completion time − Arrival time. WT = TAT − Burst time. Response time = time of first run − arrival time.

Q. Which scheduling algorithm gives the minimum average waiting time?

A. SJF (shortest job first) is optimal for average waiting time, but it needs to know burst times in advance and can starve long jobs.

Q. What is starvation and how does aging help?

A. Starvation means a low-priority process never gets the CPU. Aging gradually raises the priority of processes that have waited long, so they eventually run.

Q. How does Round Robin work?

A. Each process gets a fixed time quantum in FIFO order; when it runs out, the process goes to the back of the queue. A small quantum means more context switches, and a huge quantum turns it into FCFS.

Concurrency

Q. What is a deadlock? What are the four conditions?

A. A set of processes each waiting for a resource held by another. The four Coffman conditions: mutual exclusion, hold and wait, no preemption, circular wait. All four must hold.

Q. How can deadlocks be handled?

A. Prevention (break one condition), avoidance (the Banker's algorithm keeps the system in a safe state), detection and recovery, or ignoring them (the ostrich approach used by most desktop OSes).

Q. What is a safe state in the Banker's algorithm?

A. A state where some order of the processes (the safe sequence) lets each one get its remaining Need from Work, finish, and return its Allocation. Need = Max − Allocation. If no such order exists the state is unsafe and deadlock may happen.

Q. Why is it called the Banker's algorithm?

A. Like a bank that never lends out cash so that it can no longer meet every customer's maximum demand, the OS grants a request only if the system stays in a safe state. It was designed by Dijkstra.

Q. What is a semaphore?

A. An integer synchronisation variable with atomic wait (P) and signal (V) operations. A binary semaphore works like a mutex; a counting semaphore controls access to n identical resources.

Memory

Q. Paging vs segmentation?

A. Paging splits memory into fixed-size pages and frames, which avoids external fragmentation. Segmentation uses variable-size logical units (code, stack, data), which can cause external fragmentation.

Q. First Fit vs Best Fit vs Worst Fit?

A. First Fit uses the first free block that is big enough (fastest). Best Fit uses the smallest block that fits (least leftover). Worst Fit uses the largest block (biggest leftover). All are contiguous allocation and suffer external fragmentation.

Q. Internal vs external fragmentation?

A. Internal: wasted space inside an allocated block (e.g. fixed partitions or the last page). External: enough total free memory exists but it is split into holes too small to use. Fix external fragmentation with compaction or paging.

Q. What is virtual memory and thrashing?

A. Virtual memory lets a process use more memory than physical RAM by keeping some pages on disk (demand paging). Thrashing is when the system spends more time swapping pages than executing.

Q. Name some page-replacement algorithms.

A. FIFO, Optimal (replace the page used farthest in the future), LRU (least recently used). FIFO can suffer Belady's anomaly: more frames, more faults.

Shell

Q. What is the shebang line?

A. #!/bin/bash on the first line tells the kernel which interpreter runs the script. It only counts if it really is line 1.

Q. What are $0, $1, $#, $@, $? and $$?

A. $0 is the script name, $1 the first argument, $# the number of arguments, $@ all arguments, $? the last exit status (0 = success), $$ the PID of the current shell.

Q. What do the permissions in chmod 755 mean?

A. Owner 7 = rwx, group 5 = r-x, others 5 = r-x. r = 4, w = 2, x = 1.

Linux

Q. Hard link vs soft link?

A. A hard link is another name for the same inode; it survives deleting the original and can't cross filesystems. A soft (symbolic) link is a path pointer; it breaks if the target is removed (ln -s).