Unit2 - Subjective Questions
CSE325 • Practice Questions with Detailed Answers
Describe the steps required to create and execute a Shell Script. How are permissions changed to make a script executable?
Creating and Executing a Shell Script:
-
Creation: Open a text editor (like
vi,nano, orgedit) and write the script commands. The first line should be the Shebang (#!) line, specifying the interpreter.
bash!/bin/bash
echo "Hello World"
-
Saving: Save the file with a specific name, conventionally using the
.shextension (e.g.,myscript.sh). -
Permissions: By default, created files may not have execute permissions. Use the
chmodcommand to modify permissions.- Syntax:
chmod +x filename - Example:
chmod +x myscript.sh
- Syntax:
-
Execution: Run the script using one of the following methods:
- Relative path:
./myscript.sh - Absolute path:
/home/user/myscript.sh - Using the shell explicitly:
sh myscript.shorbash myscript.sh
- Relative path:
Differentiate between Environment Variables and User-Defined Variables in Linux Shell scripting with examples.
Difference between Environment and User-Defined Variables:
| Feature | Environment Variables | User-Defined Variables |
|---|---|---|
| Definition | Variables that affect the behavior of the shell and the user interface environment. | Variables created and defined by the user for a specific script or session. |
| Scope | Global (available to child processes/shells). | Local (available only to the current shell/script unless exported). |
| Convention | Usually named in UPPERCASE. | Usually named in lowercase (though not strictly enforced). |
| Examples | HOME, SHELL. |
count=10, name="John". |
| Declaration | Pre-defined by the system (can be viewed using printenv). |
variable_name=value |
Example:
- User Variable:
x=10(Only visible in current shell). - Env Variable:
export PATH=$PATH:/new/path(Modifies system path for child processes).
Explain how to perform arithmetic operations in shell scripting using expr. What are the limitations of expr?
The expr command evaluates expressions and prints the result to standard output. It handles integer arithmetic.
Syntax:
expr item1 operator item2
Key Rules:
- Spaces: There must be spaces between the operator and the operands.
- Correct:
expr 5 + 2 - Incorrect:
expr 5+2
- Correct:
- Meta-characters: Certain characters like multiplication (
*) and parentheses must be escaped using a backslash (\) because they have special meaning in the shell.
Examples:
- Addition:
sum=a + $b) - Multiplication:
mul=a \* $b)
Limitations:
- It creates a new process for every execution (slower in loops).
- It cannot handle floating-point numbers (decimals). It only supports integers.
How can floating-point arithmetic be performed in shell scripting? Explain the usage of the bc command with an example.
Standard shell arithmetic (like expr or $((...))) does not support floating-point numbers. The bc (Basic Calculator) command is used for this purpose. It is an arbitrary precision calculator language.
Using bc:
It is often used with the pipe (|) to pass the expression to the calculator.
Syntax:
variable=$(echo "options; expression" | bc)
The scale variable:
To perform division with decimal points, the scale variable must be defined inside bc to specify the number of decimal places.
Example:
Calculate the area of a circle where .
bash
radius=2.5
3.14 2.5 2.5
area=radius * $radius" | bc)
echo "Area is: $area"
Output: Area is: 19.62
Explain the concept of Input/Output Redirection in Linux. Describe the operators >, >>, and <.
I/O Redirection allows users to change the source of input or the destination of output for commands.
-
Standard Output Redirection (
>):- Redirects the output of a command to a file.
- Behavior: It overwrites the file if it exists, or creates a new one.
- Example:
ls -l > filelist.txt(Saves directory listing tofilelist.txt).
-
Append Output (
>>):- Redirects output to a file but preserves existing content.
- Behavior: It appends the new output to the end of the file.
- Example:
echo "New Log Entry" >> log.txt.
-
Standard Input Redirection (
<):- Feeds the content of a file as input to a command.
- Example:
wc -l < filelist.txt(Counts lines infilelist.txtwithout passing the filename as an argument).
What are Pipes in shell scripting? How are they different from I/O redirection? Provide an example combining both.
Pipes (|):
A pipe creates a communication channel between two processes. It takes the Standard Output (stdout) of the command on the left and passes it as Standard Input (stdin) to the command on the right.
Difference from Redirection:
- Redirection (
>) connects a command to a file. - Pipes (
|) connect a command to another command.
Example combining Pipes and Redirection:
Find the number of files containing the word "error" and save the count to a file.
bash
grep "error" application.log | wc -l > error_count.txt
grep: Searches for "error".|: Passes the matching lines towc.wc -l: Counts the lines.>: Writes the final number toerror_count.txt.
Write a shell script to determine if a number entered by the user is Positive, Negative, or Zero using if-elif-else constructs.
Below is the script demonstrating the if-elif-else conditional structure.
bash
!/bin/bash
echo "Enter a number:"
read num
if [ $num -gt 0 ]
then
echo "$num is a Positive number."
elif [ $num -lt 0 ]
then
echo "$num is a Negative number."
else
echo "The number is Zero."
fi
Explanation:
read num: Takes input.-gt: Greater than operator.-lt: Less than operator.fi: Closes the if block.
Explain the syntax of the case statement in shell scripting. Create a simple menu-driven calculator script (Add, Sub, Mul, Div).
Syntax of case statement:
bash
case $variable in
pattern1) commands ;;
pattern2) commands ;;
*) default_commands ;;
esac
Menu-Driven Calculator Script:
bash
!/bin/bash
echo "Enter two numbers:"
read a
read b
echo "Select Operation:"
echo "1. Add"
echo "2. Subtract"
echo "3. Multiply"
echo "4. Divide"
read choice
case $choice in
1) res=a + $b" | bc)
echo "Result: $res" ;;
2) res=a - $b" | bc)
echo "Result: $res" ;;
3) res=a $b" | bc)
echo "Result: $res" ;;
4) res=a / $b" | bc)
echo "Result: $res" ;;
) echo "Invalid choice" ;;
esac
Compare the while loop and the until loop in shell scripting with appropriate syntax and examples.
Comparison:
| Feature | while Loop |
until Loop |
|---|---|---|
| Logic | Executes the block as long as the condition is TRUE. | Executes the block as long as the condition is FALSE (runs until it becomes true). |
| Syntax | while [ condition ] |
until [ condition ] |
1. While Loop Example:
Print numbers 1 to 5.
bash
i=1
while [ $i -le 5 ]
do
echo $i
((i++))
done
2. Until Loop Example:
Print numbers 1 to 5 (loop runs until is greater than 5).
bash
i=1
until [ $i -gt 5 ]
do
echo $i
((i++))
done
Explain the for loop construct in shell scripting. Provide examples for iterating over a list of items and a C-style for loop.
The for Loop:
Used to iterate over a list of values or a range of numbers.
1. Iterating over a list (Classic Shell style):
Syntax: for var in list; do ... done
Example (Iterating over files):
bash
for file in *.txt
do
echo "Processing $file"
done
2. C-Style For Loop:
Syntax: for (( init; condition; increment )); do ... done
Example (Counting 1 to 5):
bash
for (( i=1; i<=5; i++ ))
do
echo "Number: $i"
done
What are Indexed Arrays in shell scripting? How do you declare, assign values, and access elements in an indexed array?
Indexed Arrays: Arrays where elements are stored using integer indices (starting from 0).
-
Declaration:
- Explicit:
declare -a my_array - Implicit: Just assigning values creates it.
- Explicit:
-
Assignment:
- Individual:
my_array[0]="Apple" - Compound:
my_array=("Apple" "Banana" "Cherry")
- Individual:
-
Accessing Elements:
- Single Element:
${my_array[1]}(Output: Banana) - All Elements:
{my_array[*]} - Array Length:
${#my_array[@]}
- Single Element:
Example:
bash
fruits=("Apple" "Mango" "Grape")
echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"
Describe Associative Arrays in shell scripting. How do they differ from indexed arrays? Provide an example.
Associative Arrays:
Also known as dictionaries or hashmaps, these arrays use strings (keys) as indices instead of integers. They are available in Bash version 4.0+.
Difference:
- Indexed: Keys are Integers (0, 1, 2...).
- Associative: Keys are Strings ("name", "age", "city").
Declaration (Mandatory):
You must declare them using declare -A.
Example:
bash
Declare
declare -A student
Assign
student[name]="Alice"
student[id]="S101"
student[score]="90"
Access
echo "Student Name: ${student[name]}"
Iterate Keys
for key in "${!student[@]}"
do
echo "{student[$key]}"
done
How are User-Defined Functions created in shell scripts? Explain how parameters are passed to functions with an example.
Creating Functions:
Functions are blocks of code that can be reused. They are defined using the function keyword or just the name followed by parentheses.
Syntax:
bash
function_name () {
commands
}
Parameter Passing:
Shell functions do not declare arguments in parentheses. Instead, arguments passed to the function are accessed using positional parameters (2, etc.) inside the function.
Example:
bash
Definition
greet_user () {
echo "Hello, 2."
}
Calling the function
greet_user "John" 101
Output: Hello, John! Your ID is 101.
Note: $0 inside the function is the script name, not the function name.
Explain the significance of the following positional parameters and special variables: #, ?, and $$.
These are special variables used to access arguments and process status.
$0: The name of the script or the command currently executing.$#: The count of arguments passed to the script or function.- *`` for looping.
$?: The exit status of the last executed command (0 usually means success, non-zero means failure).$$: The Process ID (PID) of the current shell script instance. Often used for creating unique temporary filenames.
Write a shell script to calculate the factorial of a given number using a while loop.
The factorial of a number is defined as .
Script:
bash
!/bin/bash
echo "Enter a number:"
read n
factorial=1
counter=$n
Check if number is negative
if [ $n -lt 0 ]; then
echo "Factorial is not defined for negative numbers."
exit 1
fi
while [ $counter -gt 0 ]
do
factorial = factorial * counter
factorial=$(( factorial * counter ))
# Decrement counter
((counter--))
done
echo "Factorial of factorial"
Write a shell script to generate the Fibonacci series up to terms.
The Fibonacci series starts with 0 and 1, and the next number is the sum of the previous two ().
Script:
bash
!/bin/bash
echo "Enter the number of terms:"
read N
a=0
b=1
echo "Fibonacci Series:"
for (( i=0; i<N; i++ ))
do
echo -n "$a "
fn=$((a + b))
a=$b
b=$fn
done
echo "" # New line
Explanation:
- Initialize
a=0,b=1. - Loop times.
- Print
a. - Calculate next term
fn = a + b. - Update
atobandbtofn.
Explain the File Test Operators in shell scripting used to check file attributes (e.g., -f, -d, -r, -w, -x, -s).
File test operators are used within if conditions (e.g., if [ -f file ]) to check file properties.
-f file: True if the file exists and is a regular file (not a directory or device).-d file: True if the file exists and is a directory.-r file: True if the file exists and is readable by the user.-w file: True if the file exists and is writable.-x file: True if the file exists and is executable.-s file: True if the file exists and has a size greater than zero (not empty).-e file: True if the file exists (regardless of type).
Example:
bash
if [ -d "/home/user/data" ]; then
echo "Directory exists"
fi
Write a shell script that accepts a filename as a command-line argument and checks if it exists. If it exists, display its permissions; otherwise, create it.
bash
!/bin/bash
Check if argument is passed
if [ $# -eq 0 ]; then
echo "Usage: $0 filename"
exit 1
fi
filename=$1
if [ -e "$filename" ]; then
echo "File '$filename' exists."
Display permissions using ls -l
ls -l "$filename"
if [ -w "$filename" ]; then
echo "File is writable."
else
echo "File is not writable."
fi
else
echo "File does not exist. Creating it now..."
touch "$filename"
echo "File '$filename' created."
fi
What are the loop control statements break and continue? Explain their behavior with an example.
These statements alter the normal flow of loops (for, while, until).
break: Terminates the loop immediately and transfers control to the statement following thedonekeyword. It is used to exit a loop early.continue: Skips the remaining commands in the current iteration of the loop and jumps back to the condition check for the next iteration.
Example:
bash
for i in {1..5}
do
if [ $i -eq 2 ]; then
continue # Skip 2
fi
if [ $i -eq 4 ]; then
break # Stop at 4 (do not print 4 or 5)
fi
echo "Number: $i"
done
Output:
Number: 1
Number: 3
How can you debug a shell script? Explain the execution modes -v and -x.
Debugging helps locate errors in the script logic or syntax.
1. Verbose Mode (-v):
- Function: Prints shell input lines as they are read.
- Usage:
bash -v script.sh - Purpose: Helps to see the code structure before execution.
2. X-trace / Debug Mode (-x):
- Function: Prints commands and their arguments as they are executed.
- Usage:
bash -x script.sh - Output: Lines usually start with
+to indicate the trace. - Purpose: Shows variable expansions and the exact command being run.
Embedding in Script:
You can also add set -x inside the script to start debugging from that point and set +x to stop it.