MODULE-4 Introduction to the Shell Scripting - Introduction to Shell Scripting, Shell
Scripts, read, Command Line Arguments, Exit Status of a Command, The Logical
Operators && and ||, exit, if, and case conditions, expr, sleep and wait, while, until, for, $,
@, redirection. The here document, set, trap, Sample Validation and Data Entry Scripts
Shell Scripting in UNIX
a) What is a shell in UNIX? Explain the role of shell scripting in UNIX
systems. (7 marks)
Shell in UNIX:
● A shell is a command-line interpreter that provides an interface between the user and
the UNIX operating system.
● It interprets user commands and passes them to the kernel for execution.
Role of Shell Scripting:
● Automates repetitive tasks (e.g., backups, file processing).
● Enables creation of custom commands and workflows.
● Used for system administration, configuration, user management, and more.
● Allows conditional logic, loops, and variables, making UNIX powerful and programmable.
Common shells: sh, bash, ksh, zsh.
b) Define a shell script. How do you create and execute a basic shell
script? (7 marks)
Shell Script:
● A shell script is a text file containing a series of UNIX commands written in shell syntax.
● It is interpreted and executed by the shell.
Steps to Create and Execute:
Create the script:
nano [Link]
1.
Write contents:
#!/bin/bash
echo "Hello, World!"
2.
Make it executable:
chmod +x [Link]
3.
Execute the script:
./[Link]
4.
c) Write a simple shell script that reads a user’s name and prints a greeting
message. (6 marks)
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name! Welcome to UNIX."
Shell Scripting: Input and Arguments
a) Explain the use of read command in shell scripting with an example. (6
marks)
read Command:
● Used to take input from the user during script execution.
Syntax:
read variable_name
Example:
echo "Enter your age:"
read age
echo "You are $age years old."
b) What are command line arguments? How do you access them inside a
shell script? (7 marks)
Command Line Arguments:
● These are values passed to a shell script at the time of execution.
● They allow the script to be dynamic and reusable.
Accessing Arguments:
● $0 → Script name
● $1, $2, ... → First, second, ... arguments
● $# → Number of arguments
● $@ or $* → All arguments
Example:
./[Link] apple banana
Inside script:
echo $1 # apple
echo $2 # banana
c) Write a shell script that takes two numbers as command line arguments
and displays their sum. (7 marks)
#!/bin/bash
num1=$1
num2=$2
sum=$((num1 + num2))
echo "Sum: $sum"
Usage:
./[Link] 5 10
# Output: Sum: 15
Exit Status and Logical Operators
a) What is the exit status of a command? How can you use it in a script? (6
marks)
Exit Status:
● A value returned by a command or script to indicate success or failure.
● 0 → success
● Non-zero → error or failure
Access:
echo $?
Usage in Script:
ls [Link]
if [ $? -eq 0 ]; then
echo "File found."
else
echo "File not found."
fi
b) Explain the logical operators && and || in shell scripting with examples.
(7 marks)
Logical AND &&:
● Executes the second command only if the first succeeds (exit status 0).
mkdir newdir && cd newdir
Logical OR ||:
● Executes the second command only if the first fails (non-zero exit status).
cd mydir || echo "Directory does not exist."
These operators are useful for conditional execution without full if statements.
c) Write a script that executes two commands where the second runs only
if the first succeeds. (7 marks)
#!/bin/bash
echo "Creating backup directory..."
mkdir backup && echo "Directory created successfully."
If mkdir backup succeeds, the message is printed. If it fails, nothing happens after.
✅ Shell Scripting: Control, Execution, and Loops
a) Describe the use of exit command in shell scripts. (5 marks)
Use of exit Command:
● The exit command is used to terminate a shell script and optionally return a status
code to the calling process or shell.
Purpose:
1. Signals the end of the script.
2. Returns an exit status:
○ 0 for success
○ Non-zero for failure or specific error codes
Example:
if [ "$USER" != "root" ]; then
echo "Run as root."
exit 1
fi
b) Explain if and case conditional statements with syntax. (8 marks)
if Statement:
Used for conditional execution of code.
Syntax:
if [ condition ]; then
commands
elif [ another_condition ]; then
commands
else
commands
fi
Example:
if [ $x -gt 0 ]; then
echo "Positive"
else
echo "Non-positive"
fi
case Statement:
Simplifies multiple condition checking, especially for menu-driven programs.
Syntax:
case $variable in
pattern1) commands ;;
pattern2) commands ;;
*) default commands ;;
esac
Example:
case $1 in
start) echo "Starting..." ;;
stop) echo "Stopping..." ;;
*) echo "Invalid option" ;;
esac
c) Write a shell script using if to check if a file exists. (7 marks)
#!/bin/bash
echo "Enter filename:"
read file
if [ -f "$file" ]; then
echo "File '$file' exists."
else
echo "File '$file' does not exist."
fi
✅ Shell Scripting: Commands and Process Control
a) What is the expr command? Give examples of its usage. (6 marks)
expr Command:
● Used for integer arithmetic and string operations in shell scripts.
Examples:
Addition:
expr 5 + 3 # Output: 8
1.
Multiplication:
expr 4 \* 2 # Output: 8 (Note: `*` must be escaped)
2.
String Length:
expr length "Hello" # Output: 5
3.
b) Explain the purpose of sleep and wait commands in shell scripting. (7
marks)
sleep:
● Pauses the script for a specified amount of time.
● Used to add delays between commands or simulate processing time.
Syntax:
sleep [seconds]
wait:
● Waits for background processes to complete before continuing.
● Ensures sequential execution when using & (background tasks).
Syntax:
wait [PID]
Use Cases:
● sleep: animations, delays between retries
● wait: coordination of multiple script processes
c) Write a script demonstrating the use of sleep and wait. (7 marks)
#!/bin/bash
echo "Starting task..."
(sleep 5; echo "Task done!") &
wait
echo "All background tasks completed."
✅ Shell Scripting: Loops
a) Explain the loops: while, until, and for in shell scripting. (9 marks)
1. while Loop:
● Executes as long as the condition is true.
Syntax:
while [ condition ]; do
commands
done
Example:
count=1
while [ $count -le 5 ]; do
echo $count
count=$((count + 1))
done
2. until Loop:
● Executes until the condition becomes true (opposite of while).
Syntax:
until [ condition ]; do
commands
done
Example:
count=1
until [ $count -gt 5 ]; do
echo $count
count=$((count + 1))
done
3. for Loop:
● Iterates over a list or range.
Syntax:
for var in list; do
commands
done
Example:
for i in 1 2 3 4 5; do
echo $i
done
b) Write a shell script using a for loop to print numbers from 1 to 5. (5
marks)
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
c) Write a script using while loop that reads user input until "exit" is
entered. (6 marks)
#!/bin/bash
while true; do
echo "Enter text (type 'exit' to quit):"
read input
if [ "$input" = "exit" ]; then
break
fi
echo "You entered: $input"
done
✅ Special Variables, Redirection, and Here Documents
a) What do the special variables $, $@, and $# represent in shell scripting?
(7 marks)
Variable Description Example Usage
$ Process ID of the currently running echo $$ → Displays PID
script/process
$@ All the command-line arguments passed to for arg in "$@"; do echo
the script $arg; done
$# Total number of command-line arguments echo "Total args: $#"
Example Script:
#!/bin/bash
echo "Script PID: $$"
echo "All arguments: $@"
echo "Number of arguments: $#"
b) Explain input/output redirection with examples. (7 marks)
I/O Redirection in Shell:
1. Output Redirection (> and >>)
○ >: Overwrites file
○ >>: Appends to file
echo "Hello" > [Link] # Creates or overwrites
echo "World" >> [Link] # Appends to file
2.
3. Input Redirection (<)
○ Reads input from a file
sort < [Link]
4.
5. Error Redirection
○ Redirect stderr: 2>
○ Redirect both stdout and stderr: &>
command 2> [Link]
command &> [Link]
6.
c) What is a "here document"? Illustrate with a sample script. (6 marks)
Here Document (heredoc):
● Allows multi-line input within the script using <<.
Syntax:
command <<DELIMITER
text lines
DELIMITER
Example Script:
#!/bin/bash
cat <<EOF
This is a test.
Multiple lines printed.
EOF
Used commonly for user prompts, documentation, or testing.
✅ Set, Trap, and Signal Handling
a) What does the set command do in shell scripting? How can it be used
for debugging? (6 marks)
set Command:
● Modifies shell behavior or variables.
For Debugging:
● set -x: Enables debug mode; displays each command before execution.
● set +x: Disables debug mode.
Example:
#!/bin/bash
set -x
echo "Start"
ls
set +x
echo "Done"
Other Common Options:
● set -e: Exit on any error
● set -u: Treat unset variables as an error
b) Explain the purpose of the trap command with an example. (7 marks)
trap Command:
● Used to catch and handle signals (like CTRL+C, SIGINT, etc.) during script execution.
Purpose:
● Clean up resources, show custom messages, avoid script crashes.
Example:
trap "echo 'Script interrupted'; exit" SIGINT
This traps Ctrl+C (SIGINT) and executes a message before exiting.
c) Write a script that traps the SIGINT signal and displays a message before
exiting. (7 marks)
#!/bin/bash
trap "echo 'Interrupt signal caught. Exiting safely...'; exit" SIGINT
echo "Press Ctrl+C to test trap..."
while true; do
sleep 1
done
✅ Validation and Data Entry Scripts
a) Write a shell script for validating a user-entered email address. (8 marks)
#!/bin/bash
echo "Enter email:"
read email
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$ ]]; then
echo "Valid email."
else
echo "Invalid email format."
fi
Uses a regular expression to validate email pattern.
b) Create a sample data entry script that asks for username and password
and confirms the entry. (7 marks)
#!/bin/bash
read -p "Enter username: " username
read -s -p "Enter password: " password
echo
read -s -p "Confirm password: " confirm
echo
if [ "$password" = "$confirm" ]; then
echo "User $username added successfully."
else
echo "Passwords do not match. Try again."
fi
● -s hides password input
● Confirms password before proceeding
c) Explain how validation improves script robustness. (5 marks)
Importance of Validation in Scripts:
1. Prevents Errors:
○ Stops scripts from processing invalid inputs (e.g., empty or malformed data).
2. Improves User Experience:
○ Gives clear feedback for incorrect input and allows correction.
3. Ensures Data Integrity:
○ Accepts only expected formats (like valid emails, numbers, file paths).
4. Security:
○ Prevents injection attacks and misuse by verifying inputs.
5. Reliable Execution:
○ Avoids unexpected script crashes or bugs during execution.