5th Sem BCA UNIX PROGRAMMING UNIT-4
1. Explain decision making structures in shell scripting with example.
ANS:
Decision-Making Structures in Shell Scripting
In Unix shell scripting, decision-making structures allow a script to evaluate conditions and execute commands based
on whether the condition is true or false. These structures help automate logical operations like checking file existence,
comparing numbers/strings, validating user inputs, and controlling program flow.
Shell uses commands and expressions inside [ ], [[ ]], or test to evaluate conditions. Decision-making statements mainly
include:
1. if statement
2. if-else statement
3. elif (else-if) ladder
4. nested if
5. case (switch) statement
1. IF Statement
Definition
The if statement executes a block of commands only if the specified condition is true.
Syntax
if [ condition ]
then
commands
fi
Example
echo "Enter a number:"
read n
if [ $n -gt 0 ]
then
echo "Positive number"
fi
Explanation:
If the user input is greater than 0, the message is displayed; otherwise nothing happens.
2. IF – ELSE Statement
Definition
This structure handles two-way decisions. One block executes if the condition is true, and the other executes if the
condition is false.
Syntax
if [ condition ]
then
commands_if_true
else
commands_if_false
fi
Example
echo "Enter age:"
read age
if [ $age -ge 18 ]
then
echo "Eligible to vote"
else
1
5th Sem BCA UNIX PROGRAMMING UNIT-4
echo "Not eligible to vote"
fi
3. ELSE–IF Ladder (elif)
Definition
Used when multiple conditions need to be checked in sequence. Only the first true condition is executed.
Syntax
if [ condition1 ]
then
commands1
elif [ condition2 ]
then
commands2
elif [ condition3 ]
then
commands3
else
commands_default
fi
Example
echo "Enter marks:"
read m
if [ $m -ge 90 ]
then
echo "Grade A"
elif [ $m -ge 75 ]
then
echo "Grade B"
elif [ $m -ge 60 ]
then
echo "Grade C"
else
echo "Fail"
fi
4. NESTED IF
Definition
An if statement inside another if is called a nested if. It is used for multi-level decision making.
Syntax
if [ condition1 ]
then
if [ condition2 ]
then
commands
fi
fi
Example
echo "Enter username:"
read user
if [ $user = "admin" ]
2
5th Sem BCA UNIX PROGRAMMING UNIT-4
then
echo "Enter password:"
read pass
if [ $pass = "1234" ]
then
echo "Login successful"
else
echo "Incorrect password"
fi
else
echo "Unknown user"
fi
5. CASE Statement (Switch)
Definition
The case statement matches a value against different patterns. It simplifies multiple-choice decision making and reduces
complex if-else chains.
Syntax
case value in
pattern1) commands ;;
pattern2) commands ;;
pattern3) commands ;;
*) default_commands ;;
esac
Example
echo "Enter choice (1-3):"
echo "1. List Files"
echo "2. Show Date"
echo "3. Show Current Directory"
read choice
case $choice in
1) ls ;;
2) date ;;
3) pwd ;;
*) echo "Invalid Choice" ;;
esac
Common Conditional Expressions Used
1. File Test Operators
Operator Meaning
-f file True if file exists and is a regular file
-d file True if directory exists
-r file True if file is readable
-w file True if writable
-x file True if executable
Example
if [ -f [Link] ]
then
echo "File exists"
3
5th Sem BCA UNIX PROGRAMMING UNIT-4
fi
2. Numeric Comparison
Operator Meaning
-eq equal
-ne not equal
-gt greater than
-lt less than
-ge greater or equal
-le less or equal
Example
if [ $a -gt $b ]; then echo "A is greater"; fi
3. String Comparison
Operator Meaning
= equal
!= not equal
-z string is empty
-n string is not empty
2. Explain the purpose and usages of key UNIX utilities like cut, paste, join and tr with examples of how they work.
ANS:
UNIX provides a powerful collection of text-processing utilities that help users manipulate, extract, format, and combine
textual data. Among these, cut, paste, join, and tr are widely used in shell scripting and data processing tasks. These
commands operate on files line-by-line and are highly efficient for handling structured data such as CSV files, records,
logs, and reports.
1. cut Command
Purpose
The cut command extracts specific columns or fields from a text file. It is commonly used for splitting data based on
character positions or delimiters like commas, spaces, or tabs.
Common Options
-c : Select specific character positions.
-f : Select fields.
-d : Specify delimiter (default: TAB).
Example 1 – Extract Characters
echo "COMPUTER" | cut -c 1-3
Output:
COM
Example 2 – Extract Fields from CSV File
File: [Link]
101,John,Manager,45000
102,Rita,Clerk,25000
Command:
cut -d "," -f 1,2 [Link]
Output:
101,John
102,Rita
4
5th Sem BCA UNIX PROGRAMMING UNIT-4
Usage: Useful for extracting selected columns from structured records.
2. paste Command
Purpose
The paste command merges lines of two or more files horizontally, meaning it combines corresponding lines using a
delimiter (default TAB).
Common Options
-d : Specify a delimiter.
-s : Merge lines serially instead of parallel.
Example – Merging Two Files Side-by-Side
File1: [Link]
John
Rita
Mary
File2: [Link]
80
70
90
Command:
paste [Link] [Link]
Output:
John 80
Rita 70
Mary 90
Example – Using a Delimiter
paste -d "," [Link] [Link]
Output:
John,80
Rita,70
Mary,90
Usage: Often used to create combined reports or merge related file content.
3. join Command
Purpose
The join command combines lines of two files based on a common field, similar to relational database join operations.
It is useful for connecting data from different files using a key.
Important Requirement
The files must be sorted on the joining field.
Common Options
-1 : Field number in first file.
-2 : Field number in second file.
-t : Specify delimiter.
Example – Joining Two Files
File1: [Link]
101 John
5
5th Sem BCA UNIX PROGRAMMING UNIT-4
102 Rita
103 Mary
File2: [Link]
101 45000
102 25000
103 55000
Command:
join [Link] [Link]
Output:
101 John 45000
102 Rita 25000
103 Mary 55000
Example – Join on Custom Field
If both files are comma-separated:
join -t "," -1 1 -2 1 [Link] [Link]
Usage: Used for merging datasets, creating reports, and linking relational data.
4. tr Command (Translate Command)
Purpose
The tr command translates, deletes, or compresses characters. It works on single characters (not words) and is often
used for case conversion, removing unwanted characters, or squeezing repeated characters.
Common Options
No option required for translation.
-d : Delete characters.
-s : Squeeze repeated characters.
Example 1 – Convert Lowercase to Uppercase
echo "unix programming" | tr "a-z" "A-Z"
Output:
UNIX PROGRAMMING
Example 2 – Delete Digits
echo "abc123de45" | tr -d "0-9"
Output:
abcde
Example 3 – Squeeze Repeated Spaces
echo "Welcome to Unix" | tr -s " "
Output:
Welcome to Unix
Usage: Used for data cleaning, case conversion, and format correction.
3. What are loops in shell scripting? Explain for loop, while loop, and until loop in detail with proper syntax and
examples. Compare these loops based on their usage.
ANS:
In shell scripting, a loop is a control structure that allows a set of commands to be executed repeatedly as long as a given
condition is true or based on a list of values. Loops help automate repetitive tasks such as processing files, reading user
input, executing commands multiple times, and working with lists or ranges.
6
5th Sem BCA UNIX PROGRAMMING UNIT-4
Shell supports three primary types of loops:
1. for loop
2. while loop
3. until loop
Each loop serves different purposes depending on the nature of the repetition.
1. For Loop
Purpose
The for loop iterates over a list of items, numbers, filenames, or words. It is used when the number of iterations is known
in advance.
Syntax
for variable in list
do
commands
done
Example 1 – Printing numbers 1 to 5
for i in 1 2 3 4 5
do
echo "Number: $i"
done
Example 2 – Iterating over files
for f in *.txt
do
echo "Processing file: $f"
done
Example 3 – Using seq
for i in $(seq 1 5)
do
echo $i
done
Explanation:
The loop runs for each item in the list and executes the commands inside the do…done block.
2. While Loop
Purpose
The while loop executes a block of commands as long as a condition remains true. It is used when the number of
iterations is not fixed and depends on runtime conditions.
Syntax
while [ condition ]
do
commands
done
Example 1 – Print numbers from 1 to 5
i=1
while [ $i -le 5 ]
7
5th Sem BCA UNIX PROGRAMMING UNIT-4
do
echo "Value: $i"
i=$((i + 1))
done
Example 2 – Read file line by line
while read line
do
echo "$line"
done < [Link]
Explanation:
The loop continues as long as the condition evaluates to true. When the condition becomes false, the loop stops.
3. Until Loop
Purpose
The until loop is similar to the while loop but it runs until the condition becomes true.
In other words, the loop continues as long as the condition is false.
Syntax
until [ condition ]
do
commands
done
Example 1 – Count from 1 to 5
i=1
until [ $i -gt 5 ]
do
echo "Value: $i"
i=$((i + 1))
done
Example 2 – Wait until a file exists
until [ -f [Link] ]
do
echo "Waiting for file..."
sleep 2
done
echo "File found!"
Explanation:
Here, the loop repeatedly runs until the test expression becomes true. This is opposite to the working of while loop.
Comparison of for, while, and until Loops
Loop Condition Type Best Used When Executes Until Practical Usage
Type
for No condition (uses a Number of iterations is List is exhausted Iterating through files, fixed
loop list) known numbers, lists
8
5th Sem BCA UNIX PROGRAMMING UNIT-4
while Loop continues while Number of iterations is Condition Reading input, waiting for
loop condition is true unknown becomes false events, processing streams
until Loop continues while We want loop to run until a Condition Waiting for files, services, or
loop condition is false condition becomes true becomes true events to occur
4. Define functions in shell scripting. Explain how functions are declared and invoked. Discuss the importance of
functions in shell programming with examples showing parameter passing and return values.
ANS:
In shell scripting, a function is a block of reusable code that performs a specific task. Functions allow programmers to
organize scripts modularly, avoid repetition, and enhance readability. Once a function is defined, it can be invoked
(called) multiple times from different parts of the script, making shell programs more structured and maintainable.
Definition of Functions in Shell Scripting
A function in shell scripting is a named section of code that performs a set of commands. Functions simplify program
structure, reduce redundancy, and allow tasks to be executed repeatedly without rewriting code.
Shell functions:
can accept parameters,
can return values,
and can share variables with the main script.
1. Declaring (Defining) a Function
There are two valid formats for defining a function.
Syntax (Method 1)
function function_name {
commands
}
Syntax (Method 2)
function_name() {
commands
}
Example of Function Definition
greet() {
echo "Hello, Welcome to Shell Scripting!"
}
2. Invoking (Calling) a Function
A function is invoked simply by using its name.
Example
greet
Complete Script:
greet() {
echo "Hello User!"
}
greet # function call
3. Importance of Functions in Shell Scripting
9
5th Sem BCA UNIX PROGRAMMING UNIT-4
Functions play a crucial role because:
1. Reusability: Write once and use multiple times.
2. Modularity: Code is organized into logical blocks.
3. Reduced Redundancy: Avoid repeating the same commands.
4. Better Maintenance: Simple updates in one place update the entire script.
5. Improved Readability: Scripts become clean, structured, and easy to understand.
6. Parameter Passing: Functions can take inputs to perform dynamic tasks.
7. Returning Values: Functions can return success/failure codes or output through echo.
4. Parameter Passing in Functions
Functions can accept arguments just like shell scripts.
$1, $2, $3, ... represent positional parameters inside functions.
$# = number of parameters
$@ and $* = all parameters
Example – Function with Parameters
add() {
sum=$(( $1 + $2 ))
echo "Sum = $sum"
}
add 5 10
Output:
Sum = 15
Explanation:
Arguments 5 and 10 are passed to the function and accessed using $1 and $2.
5. Returning Values from a Function
In shell scripting, functions can return values in two ways:
Method 1: Using return Statement
return gives a numeric value (0–255).
Usually used to indicate success or failure.
Example:
check_even() {
if [ $(( $1 % 2 )) -eq 0 ]
then
return 0 # even
else
return 1 # odd
fi
}
check_even 10
if [ $? -eq 0 ]
then
echo "Even Number"
10
5th Sem BCA UNIX PROGRAMMING UNIT-4
else
echo "Odd Number"
fi
Explanation:
Function returns 0 → Even
Function returns 1 → Odd
$? captures the return code.
Method 2: Using echo Statement (Most Common)
This method returns any type of output, not just numbers.
Example – Returning via echo
square() {
echo $(( $1 * $1 ))
}
result=$(square 7)
echo "Square = $result"
Output:
Square = 49
Explanation:
The command substitution $( ... ) stores the function output in a variable.
6. Complete Example – Function with Parameters and Return Value
calculate() {
total=$(( $1 + $2 + $3 ))
echo $total
}
result=$(calculate 10 20 30)
echo "Total = $result"
Output:
Total = 60
5. Explain the pattern matching utility ‘grep’ in UNIX. Describe its working mechanism, different types of grep, and
commonly used options with suitable examples.
ANS:
The grep command in UNIX is one of the most powerful and frequently used text-search utilities. The term grep stands
for Global Regular Expression Print, which means it searches a file or input stream for specific patterns and prints the
matching lines. It is widely used for filtering data, searching logs, debugging, and extracting meaningful information from
large text files.
Working Mechanism of grep
The working mechanism of grep is simple but powerful:
1. It takes a pattern (string or regular expression) as input.
2. It scans each line of the given file(s) from top to bottom.
3. If the pattern matches any part of the line, that line is printed as output.
4. Lines that do not match are ignored.
11
5th Sem BCA UNIX PROGRAMMING UNIT-4
Internally, grep uses pattern-matching algorithms based on regular expressions, which allow flexible searching beyond
normal text matching.
Basic syntax:
grep "pattern" filename
Example:
grep "error" [Link]
This command prints all lines containing the word error in [Link].
Types of grep
UNIX provides three major variants of grep:
1. grep (Basic grep)
This is the standard version that supports Basic Regular Expressions (BRE).
It is mostly used for normal pattern matching.
Example:
grep "hello" [Link]
2. egrep (Extended grep)
egrep stands for Extended grep, and it supports Extended Regular Expressions (ERE) such as +, ?, |, parentheses, etc.
Example using alternation:
egrep "cat|dog" [Link]
This prints lines containing either cat or dog.
3. fgrep (Fixed grep)
fgrep stands for Fixed String grep.
It does not interpret regular expressions; instead, it searches for exact strings.
It is faster when searching for plain text because it treats special characters literally.
Example:
fgrep "a+b" [Link]
Here, a+b is treated as a normal string, not a regex pattern.
Commonly Used Options in grep
1. -i : Case-insensitive search
grep -i "linux" [Link]
Matches "Linux", "LINUX", "linux", etc.
2. -n : Display line numbers
grep -n "error" [Link]
Shows which line numbers contain the word error.
3. -v : Inverted search (show lines NOT matching the pattern)
grep -v "success" [Link]
Prints all lines that do NOT contain “success”.
4. -c : Count the number of matching lines
grep -c "warning" [Link]
Outputs only the count of matched lines.
5. -r : Recursive search through directories
grep -r "main" /home/user/project/
Searches “main” in all files and subdirectories.
6. -l : Print only the filenames containing a match
12
5th Sem BCA UNIX PROGRAMMING UNIT-4
grep -l "login" *.log
Displays only the names of files where the pattern is found.
7. -w : Match whole word
grep -w "cat" [Link]
Matches only the word "cat", not "category".
8. -E : Use extended regular expressions (same as egrep)
grep -E "one|two|three" [Link]
Examples Illustrating grep Usage
Example 1: Search for a word
grep "unix" [Link]
Example 2: Search for a pattern at the beginning of a line
grep "^root" /etc/passwd
Matches lines starting with "root".
Example 3: Search for a digit using regex
grep "[0-9]" [Link]
Example 4: Highlight matches
(Many modern systems highlight automatically)
grep --color "error" [Link]
6. Write short note on: i) Decision-making structures in Shell Scripts ii) Loops in Shell Scripting iii) Shell Script
Functions iv) UNIX Text Processing Utilities (cut, paste, join, tr, uniq) v) Pattern Matching Utility – grep
ANS:
i) Decision-making structures in Shell Scripts
Decision-making structures allow a shell script to take different actions based on conditions. The most commonly used
structure is the if statement. It checks whether a given condition is true and executes commands accordingly.
if: Used when only one condition needs to be checked.
if–else: Used when both true and false conditions require actions.
if–elif–else: Used when multiple conditions need to be checked sequentially.
case (switch): Useful when there are many possible values for a single variable. It simplifies complex nested if-
else structures.
Example (if):
if [ $age -ge 18 ]
then
echo "Eligible to vote"
else
echo "Not eligible"
fi
ii) Loops in Shell Scripting
Loops are used to repeat a block of commands until a specific condition is met. Shell provides three main loops:
for loop: Iterates over a list of values.
for i in 1 2 3
do
echo $i
13
5th Sem BCA UNIX PROGRAMMING UNIT-4
done
while loop: Repeats as long as a condition remains true.
count=1
while [ $count -le 5 ]
do
echo $count
count=$((count+1))
done
until loop: Repeats until a condition becomes true (opposite of while).
num=1
until [ $num -gt 5 ]
do
echo $num
num=$((num+1))
done
iii) Shell Script Functions
Functions in shell scripting are reusable code blocks defined once and executed whenever required. They help avoid
code repetition and improve program structure.
Declaration:
myFunction() {
echo "Inside function"
}
Calling:
myFunction
Functions can also receive parameters using $1, $2, etc., and return status values using the return command.
Example with parameters:
add() {
sum=$(( $1 + $2 ))
echo "Sum is $sum"
}
add 10 20
iv) UNIX Text Processing Utilities (cut, paste, join, tr, uniq)
These utilities help manipulate and process text files:
cut: Extracts specific columns or fields from a file.
Example: cut -d: -f1 /etc/passwd → extracts usernames.
paste: Merges multiple files side-by-side.
Example: paste file1 file2.
join: Combines lines of two files based on a common field.
Example: join fileA fileB.
tr: Translates or deletes characters.
Example: tr a-z A-Z → converts lowercase to uppercase.
uniq: Removes or prints duplicate lines.
Example: uniq [Link].
14
5th Sem BCA UNIX PROGRAMMING UNIT-4
These tools are widely used in data cleanup and shell pipelines.
v) Pattern Matching Utility – grep
grep (Global Regular Expression Print) is used to search for patterns in files. It scans each line and prints lines
containing the specified pattern.
Basic usage:
grep "word" [Link]
Common options include:
-i → case-insensitive search
-n → show line numbers
-v → show lines not matching the pattern
-r → recursive search in directories
grep also supports regular expressions, allowing powerful pattern matching.
Example:
grep "^root" /etc/passwd
Prints lines starting with “root”.
15