Unit 10: Shell programming - Subjective Questions
CSE105 — Creative Engineering Workshop • Practice Questions with Detailed Answers
20 questions
Describe the general structure of a shell script. What are the essential components every shell script should contain?
A shell script is a text file containing a sequence of commands executed by the shell interpreter. Its general structure includes:
- Shebang line: The first line, e.g.,
#!/bin/bash, tells the OS which interpreter to use. - Comments: Lines beginning with
#used for documentation and explanation. - Variable declarations: Definitions such as
name="John". - Command statements: The actual instructions like
echo,ls, etc. - Control structures: Loops (
for,while) and conditionals (if,case). - Functions: Reusable blocks of code.
- Exit status: Often ends with
exit 0to indicate success.
Example:
bash
!/bin/bash
This is a simple script
name="World"
echo "Hello, $name"
exit 0
The structure promotes readability, reusability, and proper execution flow.
Explain the process of creating and executing a shell script with all the necessary steps and commands.
Creating and executing a shell script involves the following steps:
-
Create the file: Use a text editor such as
vi,nano, orgedit.
bash
nano myscript.sh -
Add the shebang and code:
bash!/bin/bash
echo "Hello World"
-
Save and exit the editor.
-
Grant execute permission using
chmod:
bash
chmod +x myscript.sh -
Execute the script in one of these ways:
./myscript.sh(requires execute permission)bash myscript.sh(does not require execute permission)sh myscript.sh
Key points:
- The
chmod +xcommand changes the file mode to make it executable. - Using
./tells the shell to look in the current directory. - The shebang determines which interpreter runs the script.
Explain the while loop in shell scripting with its syntax and a suitable example that prints numbers from 1 to 5.
The while loop repeatedly executes a block of commands as long as a specified condition remains true.
Syntax:
bash
while [ condition ]
do
commands
done
Working:
- The condition is evaluated before each iteration.
- If true, the loop body executes.
- If false, the loop terminates.
Example — Print numbers 1 to 5:
bash
!/bin/bash
i=1
while [ $i -le 5 ]
do
echo "Number: $i"
i=$((i + 1))
done
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
The variable i acts as a counter, and $((i + 1)) performs arithmetic increment. The -le operator means "less than or equal to".
Explain the for loop in shell scripting. Illustrate with two examples: one iterating over a list and one using a numeric range.
The for loop iterates over a list of items, executing the loop body once for each item.
Syntax:
bash
for variable in list
do
commands
done
Example 1 — Iterating over a list:
bash
!/bin/bash
for fruit in apple banana cherry
do
echo "Fruit: $fruit"
done
Example 2 — Numeric range using brace expansion:
bash
!/bin/bash
for i in {1..5}
do
echo "Count: $i"
done
C-style for loop (bash):
bash
for (( i=1; i<=5; i++ ))
do
echo "Value: $i"
done
Key points:
- The list can be words, numbers, files, or command output.
- Bash supports the C-style syntax for numeric iteration.
{1..5}is brace expansion generating a sequence.
What are functions in shell scripting? Explain how to define and call a function, including how to pass arguments.
A function is a reusable block of code that performs a specific task, improving modularity and reducing code duplication.
Syntax (two forms):
bash
function_name() {
commands
}
OR
function function_name {
commands
}
Calling a function: Simply use its name:
bash
function_name
Passing arguments: Arguments are accessed inside the function using $1, $2, etc.
bash
!/bin/bash
greet() {
echo "Hello, $1! You are $2 years old."
}
greet "Alice" 25
Output:
Hello, Alice! You are 25 years old.
Key points:
$1,$2are positional parameters within the function.$#gives the number of arguments passed.- Functions can return a status using
return(0–255). - Functions must be defined before they are called.
Explain arrays in shell scripting. Describe how to declare, access, and iterate over array elements with examples.
An array is a variable that stores multiple values under a single name, indexed numerically starting from 0.
Declaring an array:
bash
fruits=("apple" "banana" "cherry")
Accessing elements:
bash
echo ${fruits[0]} # apple
echo ${fruits[1]} # banana
Accessing all elements:
bash
echo ${fruits[@]} # apple banana cherry
Number of elements:
bash
echo ${#fruits[@]} # 3
Iterating over an array:
bash
!/bin/bash
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
echo "Fruit: $fruit"
done
Key points:
${array[index]}accesses a single element.${array[@]}expands to all elements.${#array[@]}gives the length.- Elements can be added dynamically:
fruits[3]="mango".
What are Interactive Shell Scripts? Explain how the read command is used to accept user input with an example.
Interactive shell scripts are scripts that prompt the user for input during execution and respond dynamically, rather than running with fixed values.
The read command reads a line of input from the user and stores it in a variable.
Syntax:
bash
read variable_name
Example:
bash
!/bin/bash
echo "Enter your name:"
read name
echo "Enter your age:"
read age
echo "Hello $name, you are $age years old."
Useful options for read:
read -p "Prompt: " var— displays a prompt on the same line.read -s var— silent input (useful for passwords).read -n 1 var— reads only one character.read -t 5 var— timeout after 5 seconds.
Example with prompt:
bash
read -p "Enter your city: " city
echo "You live in $city"
Interactive scripts make programs flexible and user-friendly.
Explain Command-Line Arguments in shell scripting. Describe the special variables $0, $1, $#, $@, and $* with an example.
Command-line arguments are values passed to a script when it is invoked, allowing scripts to behave differently based on input without hard-coding values.
Special positional variables:
| Variable | Description |
|---|---|
$0 |
Name of the script itself |
$1, $2, ... |
First, second, ... arguments |
$# |
Total number of arguments |
$@ |
All arguments as separate words |
$* |
All arguments as a single word |
$? |
Exit status of last command |
Example:
bash
!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "Total arguments: $#"
echo "All arguments: $@"
Running:
bash
./script.sh hello world
Output:
Script name: ./script.sh
First argument: hello
Second argument: world
Total arguments: 2
All arguments: hello world
Difference between $@ and $*: When quoted, "$@" treats each argument separately while "$*" joins them into a single string.
Describe the various operators in shell scripting. Explain arithmetic, relational, logical, and string operators with examples.
Shell scripting supports several categories of operators:
1. Arithmetic Operators (used with expr or $(( ))):
+addition,-subtraction,*multiplication,/division,%modulus
bash
echo $((5 + 3)) # 8
echo $((10 % 3)) # 1
2. Relational (Numeric) Operators (used with test / [ ]):
-eqequal,-nenot equal,-gtgreater than,-ltless than,-gegreater or equal,-leless or equal
bash
[ $a -gt $b ]
3. Logical Operators:
&&AND,||OR,!NOT
bash
[ $a -gt 0 ] && [ $a -lt 10 ]
4. String Operators:
=equal,!=not equal,-zstring is empty,-nstring is non-empty
bash
[ "str2" ]
[ -z "$str" ]
5. File Test Operators:
-ffile exists,-ddirectory exists,-rreadable,-wwritable,-xexecutable
These operators form the basis of decision-making and calculations in scripts.
Explain the if and if-else statements in shell scripting with syntax and examples.
The if statement executes commands based on whether a condition is true.
if syntax:
bash
if [ condition ]
then
commands
fi
if-else syntax:
bash
if [ condition ]
then
commands_if_true
else
commands_if_false
fi
Example — Check even or odd:
bash
!/bin/bash
read -p "Enter a number: " num
if [ $((num % 2)) -eq 0 ]
then
echo "$num is even"
else
echo "$num is odd"
fi
Example — Compare two numbers:
bash
!/bin/bash
a=10
b=20
if [ $a -gt $b ]
then
echo "a is greater"
else
echo "b is greater"
fi
Key points:
- The condition is enclosed in
[ ]with spaces around brackets. thenbegins the block,fi(if reversed) ends it.- Numeric comparisons use
-eq,-gt, etc.
Explain the nested if and if-elif-else (nested if) constructs in shell scripting with an example that assigns grades based on marks.
A nested if places one if statement inside another, or uses the elif (else-if) ladder to test multiple conditions sequentially.
if-elif-else syntax:
bash
if [ condition1 ]
then
commands1
elif [ condition2 ]
then
commands2
else
default_commands
fi
Example — Grade assignment:
bash
!/bin/bash
read -p "Enter marks: " marks
if [ $marks -ge 90 ]
then
echo "Grade: A"
elif [ $marks -ge 75 ]
then
echo "Grade: B"
elif [ $marks -ge 60 ]
then
echo "Grade: C"
else
echo "Grade: Fail"
fi
Truly nested if example:
bash
if [ $a -gt 0 ]
then
if [ $a -lt 100 ]
then
echo "Number between 1 and 99"
fi
fi
Key points:
elifavoids deeply nested structures, improving readability.- Each condition is tested in order; the first true block executes.
- Nested if is useful when conditions depend on prior conditions.
Explain the test command and the [] (square bracket) notation in shell scripting. How are they related?
The test command evaluates a conditional expression and returns an exit status of 0 (true) or 1 (false). It is used to make comparisons and check file properties.
Syntax:
bash
test expression
The [ ] notation is a synonym for test. In fact, [ is itself a command that requires a closing ] as its final argument.
Equivalent usages:
bash
test $a -eq $b
is the same as
[ $a -eq $b ]
Examples:
bash
Numeric test
if test $x -gt 5
then
echo "x > 5"
fi
File test
if [ -f myfile.txt ]
then
echo "File exists"
fi
Key points:
- Spaces are mandatory around
[and]and around operators. - Both perform identical evaluations.
[[ ]]is an enhanced bash version supporting pattern matching and logical operators.- Common tests:
-f(file),-d(directory),-z(empty string),-eq(numeric equality).
Explain the case statement in shell scripting with syntax. Write a script that displays a menu and performs actions using case.
The case statement provides multi-way branching by matching a variable against several patterns, offering a cleaner alternative to long if-elif chains.
Syntax:
bash
case $variable in
pattern1)
commands ;;
pattern2)
commands ;;
*)
default_commands ;;
esac
Key elements:
;;terminates each pattern block.*)is the default (matches anything).esac(case reversed) ends the statement.
Example — Menu-driven script:
bash
!/bin/bash
echo "1. Date"
echo "2. List files"
echo "3. Current directory"
read -p "Choose an option: " choice
case $choice in
1)
date ;;
2)
ls ;;
3)
pwd ;;
*)
echo "Invalid option" ;;
esac
Advantages:
- More readable than nested
iffor fixed-value comparisons. - Supports pattern matching, e.g.,
[Yy]*matches yes.
Distinguish between the while loop and the for loop in shell scripting. When would you prefer one over the other?
Both loops repeat a block of code, but they differ in how iterations are controlled.
| Aspect | for loop |
while loop |
|---|---|---|
| Iteration basis | Iterates over a fixed list or range | Iterates while a condition is true |
| Count known? | Best when number of iterations is known | Best when count is unknown |
| Condition check | Implicit (list exhaustion) | Explicit condition each iteration |
| Typical use | Processing files, list items, ranges | Reading input until EOF, waiting for a state |
for loop example:
bash
for i in 1 2 3
do
echo $i
done
while loop example:
bash
i=1
while [ $i -le 3 ]
do
echo $i
i=$((i+1))
done
When to prefer:
- Use for when iterating over a known collection or fixed number of times.
- Use while when the number of repetitions depends on a runtime condition (e.g., reading a file line by line, retrying until success).
Compare the [ ] (single bracket) and [[ ]] (double bracket) test constructs in bash. What advantages does [[ ]] offer?
Both constructs evaluate conditional expressions, but [[ ]] is a bash keyword with enhanced features, whereas [ ] is the POSIX test command.
| Feature | [ ] (test) |
[[ ]] (bash) |
|---|---|---|
| Type | External/builtin command | Shell keyword |
| Portability | POSIX-compliant, works in all shells | Bash/Ksh/Zsh specific |
| Word splitting | Occurs (needs quoting) | Suppressed (safer) |
| Pattern matching | Not supported | Supports == with globs |
| Regex | Not supported | Supports =~ operator |
| Logical operators | Uses -a, -o |
Uses &&, || |
Examples:
bash
Single bracket
if [ "$a" = "hello" ]; then echo match; fi
Double bracket with pattern
if [[ $a == hel* ]]; then echo match; fi
Regex matching
if [[ ]]; then echo "numeric"; fi
Advantages of [[ ]]:
- No word-splitting or glob issues with unquoted variables.
- Supports pattern (
==) and regex (=~) matching. - Cleaner logical operators
&&and||.
Note: Use [ ] for portable POSIX scripts and [[ ]] for bash-specific scripts.
Write a shell script using a function and a loop that calculates the factorial of a number entered by the user. Explain the logic in detail.
This program combines interactive input, a function, and a loop to compute the factorial .
Script:
bash
!/bin/bash
factorial() {
num=$1
fact=1
for (( i=1; i<=num; i++ ))
do
fact=$((fact * i))
done
echo $fact
}
read -p "Enter a number: " n
result=$(factorial $n)
echo "Factorial of $n is $result"
Logic explanation:
- Function definition:
factorial()takes one argument$1and stores it innum. - Initialization:
fact=1because the multiplicative identity is 1. - Loop: A C-style
forloop runs fromi=1tonum, multiplyingfactby eachi. - Arithmetic:
$((fact * i))performs integer multiplication. - Return via echo: The function outputs the result, captured using command substitution
$(factorial $n). - Input/Output:
readaccepts the number, and the finalechodisplays the answer.
Sample run:
Enter a number: 5
Factorial of 5 is 120
Here .
Write and explain a complete shell script that reads a list of numbers into an array, then finds and prints the largest and smallest elements.
This script demonstrates array declaration, iteration, and comparison logic.
Script:
bash
!/bin/bash
read -p "How many numbers? " count
declare -a arr
for (( i=0; i<count; i++ ))
do
read -p "Enter number i]
done
max=${arr[0]}
min=${arr[0]}
for num in "${arr[@]}"
do
if [ $num -gt $max ]
then
max=$num
fi
if [ $num -lt $min ]
then
min=$num
fi
done
echo "Largest: $max"
echo "Smallest: $min"
Explanation:
declare -a arr: Explicitly declares an indexed array.- Input loop: Reads
countvalues, storing each inarr[$i]. - Initialization:
maxandminboth start as the first element${arr[0]}. - Comparison loop: Iterates over all elements
"${arr[@]}":- If an element is greater than
max, updatemax. - If an element is smaller than
min, updatemin.
- If an element is greater than
- Output: Prints the largest and smallest values found.
Sample run:
How many numbers? 4
Enter number 1: 12
Enter number 2: 7
Enter number 3: 25
Enter number 4: 3
Largest: 25
Smallest: 3
The algorithm runs in time by making a single pass through the array.
Define a shell script and explain the role of the shebang (#!) line. What happens if the shebang is omitted?
Definition: A shell script is a plain-text file containing a series of shell commands that are executed sequentially by a command-line interpreter (shell). It automates repetitive tasks and combines multiple commands into a single executable program.
The Shebang (#!) line:
- It is the very first line of a script, written as
#!/bin/bashor#!/bin/sh. - The characters
#!are called the shebang (hash-bang). - It tells the operating system which interpreter should execute the script.
Example:
bash
!/bin/bash
echo "Running with bash"
How it works:
- When you run
./script.sh, the kernel reads the shebang and launches the specified interpreter, passing the script as input. - The path after
#!must be the absolute path to the interpreter.
If the shebang is omitted:
- The script is executed by the current/default shell when run as
./script.sh. - This may cause unexpected behavior if the default shell differs from the intended one (e.g., features written for bash failing under
dash/sh). - Explicitly running
bash script.shstill works because the interpreter is stated on the command line.
Best practice: Always include a shebang to ensure portability and predictable execution.
Describe the different ways to perform arithmetic operations in shell scripts. Explain expr, $(( )), let, and bc with examples.
The shell provides several mechanisms for arithmetic since variables are treated as strings by default.
1. expr command:
- An external command for integer arithmetic. Requires spaces around operators;
*must be escaped.
bash
result=expr 5 + 3
echo $result # 8
result=expr 4 \* 2
echo $result # 8
2. Arithmetic Expansion $(( )):
- The most common and efficient built-in method for integer math.
bash
result=$((5 + 3))
echo $result # 8
echo $((10 / 3)) # 3 (integer division)
3. let command:
- A built-in that evaluates arithmetic expressions.
bash
let result=5+3
echo $result # 8
let "x = 4 * 2"
echo $x # 8
4. bc (basic calculator):
- Used for floating-point arithmetic, which the shell cannot do natively.
bash
result=$(echo "scale=2; 10 / 3" | bc)
echo $result # 3.33
Summary:
| Method | Type | Notes |
|---|---|---|
expr |
Integer | External, needs escaping |
$(( )) |
Integer | Fast, built-in, preferred |
let |
Integer | Built-in |
bc |
Float | Supports decimals via scale |
For decimal calculations, bc is essential; for integers, $(( )) is recommended.
Write a shell script that uses command-line arguments, a case statement, and appropriate operators to build a simple calculator that adds, subtracts, multiplies, or divides two numbers. Explain the script.
This script accepts three command-line arguments — two numbers and an operator — and performs the corresponding calculation.
Script:
bash
!/bin/bash
if [ $# -ne 3 ]
then
echo "Usage: $0 num1 operator num2"
exit 1
fi
a=$1
op=$2
b=$3
case $op in
add)
echo "Result: $((a + b))" ;;
sub)
echo "Result: $((a - b))" ;;
mul)
echo "Result: $((a b))" ;;
div)
if [ $b -eq 0 ]
then
echo "Error: Division by zero"
else
echo "Result: $((a / b))"
fi ;;
)
echo "Invalid operator. Use add, sub, mul, or div." ;;
esac
Explanation:
- Argument check:
$#gives the number of arguments; if not exactly 3, it prints usage and exits with status 1. - Assignment:
$1,$2,$3are the positional parameters mapped toa,op, andb. - case statement: Matches the operator string and performs the matching arithmetic using
$(( )). - Division safety: A nested
ifchecks for division by zero before dividing. - Default
*): Handles invalid operators gracefully.
Sample run:
./calc.sh 10 add 5
Result: 15
./calc.sh 10 div 0
Error: Division by zero
This demonstrates the combined use of command-line arguments, conditional operators, and multi-way branching.
Describe the general structure of a shell script. What are the essential components every shell script should contain?
A shell script is a text file containing a sequence of commands executed by the shell interpreter. Its general structure includes:
- Shebang line: The first line, e.g.,
#!/bin/bash, tells the OS which interpreter to use. - Comments: Lines beginning with
#used for documentation and explanation. - Variable declarations: Definitions such as
name="John". - Command statements: The actual instructions like
echo,ls, etc. - Control structures: Loops (
for,while) and conditionals (if,case). - Functions: Reusable blocks of code.
- Exit status: Often ends with
exit 0to indicate success.
Example:
bash
!/bin/bash
This is a simple script
name="World"
echo "Hello, $name"
exit 0
The structure promotes readability, reusability, and proper execution flow.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →