Unit2 - Subjective Questions
CSE325 • Practice Questions with Detailed Answers
Explain the significance of the 'Shebang' line in a shell script. How do you change the permissions of a file to make it executable?
Shebang Line:
The Shebang line is the very first line of a script file. It begins with #! followed by the absolute path to the interpreter that should be used to execute the script.
- Syntax:
#!/bin/bashor#!/bin/sh - Function: It tells the kernel which interpreter (e.g., Bash, Python, Perl) to use to parse the rest of the file. If omitted, the current shell assumes the script is written in its own language, which may cause errors if the syntax differs.
Making a File Executable:
By default, created files are not executable for security reasons. To execute a script, the execute permission (x) must be added using the chmod command.
- Symbolic Mode:
chmod +x scriptname.sh(Adds execute permission for all users). - Absolute (Octal) Mode:
chmod 755 scriptname.sh(Read/Write/Execute for owner, Read/Execute for group and others).
Differentiate between Environment Variables and User-Defined Variables in Linux Shell. How can a user-defined variable be converted into an environment variable?
Difference between Environment and User-Defined Variables:
| Feature | Environment Variables | User-Defined Variables |
|---|---|---|
| Scope | Global. Available to the current shell and all child processes spawned by it. | Local. Available only to the current shell instance. |
| Convention | Usually named in UPPERCASE (e.g., PATH, HOME). |
Usually named in lowercase (though not strictly enforced). |
| Purpose | Control the behavior of the system and shell environment. | Used to store temporary data within a script or session. |
Converting User-Defined to Environment Variable:
A user-defined variable is local by default. To make it an environment variable (accessible to child scripts), use the export command.
bash
my_var="Hello"
export my_var
Or in one line:
export my_var="Hello"
Describe the usage of the expr command for arithmetic operations. What are its limitations, and how does valid shell syntax for multiplication differ when using expr?
The expr command is a legacy command-line utility used to evaluate expressions, primarily arithmetic and string comparisons.
Usage:
It prints the result of the expression to standard output.
- Addition:
expr 5 + 2 - Subtraction:
expr 5 - 2 - Division:
expr 10 / 2
Syntax and Limitations:
- Spaces: Spaces are mandatory between operators and operands.
expr 5+2will fail;expr 5 + 2works. - Integer Only:
exprtypically supports only integer arithmetic. It cannot handle floating-point numbers. - Multiplication Issue: The asterisk
*is a wildcard character in shell. Therefore, when performing multiplication, it must be escaped using a backslash\.- Incorrect:
expr 5 * 2(Shell tries to expand*to filenames). - Correct:
expr 5 \* 2.
- Incorrect:
Compare the usage of expr and bc for arithmetic operations. Write a shell command using bc to calculate the value of up to 4 decimal places.
Comparison of expr and bc:
- Data Types:
exprhandles only integers, whereasbc(Basic Calculator) is an arbitrary-precision calculator language that supports floating-point numbers. - Complexity:
expris good for simple counters.bcincludes math libraries (sine, cosine, log) and can handle complex logical statements. - Syntax:
exprrequires strict spacing and escaping of wildcards.bcusually takes input via pipes or redirection.
Calculating using bc:
To calculate floating-point results, we use the -l flag (math library) and set the scale.
bash
Formula: 4 * arctan(1) = pi
echo "scale=4; 4*a(1)" | bc -l
Output: 3.1412
Explain the concept of Input and Output Redirection in Linux. Describe the function of the operators >, >>, and <.
Redirection is the process of changing the standard input/output sources. By default, standard input (stdin) is the keyboard, and standard output (stdout) is the screen.
Operators:
-
Output Redirection (
>):- Redirects the standard output of a command to a file.
- Behavior: It overwrites the file if it exists, or creates a new one if it doesn't.
- Example:
ls > filelist.txt(Saves directory listing tofilelist.txt).
-
Append Output Redirection (
>>):- Redirects standard output to a file but appends the data to the end of the file instead of overwriting it.
- Example:
date >> logfile.txt(Adds current date to the end of existing logs).
-
Input Redirection (
<):- Feeds the content of a file into the standard input of a command.
- Example:
wc -l < filelist.txt(Counts lines infilelist.txt).
What is a Pipe (|) in shell scripting? How does it differ from I/O redirection? Provide an example combining both.
Definition:
A Pipe (|) is a mechanism that connects the Standard Output (stdout) of one command directly to the Standard Input (stdin) of another command. It allows for the chaining of utilities to perform complex tasks.
Difference from Redirection:
- Redirection: Connects a command to a file (Command File or File Command).
- Pipe: Connects a command to another command (Command Command).
Example Combining Both:
Scenario: List all files, sort them in reverse order, and save the result to a file.
bash
ls -l | sort -r > sorted_files.txt
ls -lgenerates the list.|passes that list tosort -r.>redirects the final sorted output tosorted_files.txt.
Write a shell script using a Menu-Driven approach (using case statement) to perform basic calculator operations (Add, Sub, Mul, Div) based on user choice.
bash
!/bin/bash
echo "Enter Two numbers : "
read a
read b
echo "Enter Choice :"
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read ch
case $ch in
1)res=expr b
echo "Result: $res";;
2)res=expr b
echo "Result: $res";;
3)res=expr b
echo "Result: $res";;
4)res=echo "scale=2; b" | bc
echo "Result: $res";;
*)echo "Invalid Choice";;
esac
Explanation:
- The script reads two numbers and a choice.
- The
casestatement matches variable$chagainst patterns (1, 2, 3, 4). exprhandles integer math, andbcis used for division to handle floating points.
Explain the syntax of the if-elif-else conditional statement in shell scripting. What is the role of the test command or [ ] brackets?
Syntax:
bash
if [ condition1 ]; then
commands if condition1 is true
elif [ condition2 ]; then
commands if condition2 is true
else
commands if none are true
fi
Role of test or [ ]:
- The square brackets
[ ]are actually a reference to thetestcommand. - They evaluate the expression inside them and return a status code (0 for True, 1 for False).
- Important: Spaces are mandatory after the opening bracket
[and before the closing bracket]. Without spaces, the shell treats it as a syntax error. - Example:
if [ b ]checks if variableais greater thanb.
Discuss the different forms of the for loop in shell scripting with syntax and examples.
The for loop iterates over a list of items or a sequence of numbers.
1. Iterate over a List (Strings/Files):
bash
for var in list_item1 list_item2 ...
do
command $var
done
Example: for file in *.txt; do echo "Found $file"; done
2. Iterate over a Number Range (Brace Expansion):
bash
for i in {1..5}
do
echo "Number $i"
done
3. C-Style Syntax:
Similar to C programming language.
bash
for (( i=1; i<=5; i++ ))
do
echo "Counter: $i"
done
Distinguish between the while and until looping constructs in shell scripting.
Both loops execute a block of code repeatedly based on a condition, but their logic is inverted.
1. While Loop:
- Logic: Executes the block as long as the condition is True.
- It stops when the condition becomes False.
- Syntax:
while [ condition ] - Example: Keep running while count is less than 5.
2. Until Loop:
- Logic: Executes the block as long as the condition is False.
- It stops when the condition becomes True.
- Syntax:
until [ condition ] - Example: Keep running until count is greater than 5.
Summary: until [ condition ] is effectively equivalent to while [ ! condition ].
How are Indexed Arrays declared and accessed in Bash? Provide a script snippet to iterate through all elements of an array.
Declaration:
Indexed arrays use integers as keys (starting from 0).
bash
Method 1: Explicit declaration
declare -a my_array
Method 2: Direct assignment
fruits=("Apple" "Banana" "Cherry")
Method 3: Index assignment
fruits[3]="Date"
Accessing:
- Single Element:
${fruits[1]}(Returns "Banana") - All Elements:
{fruits[*]}
Iteration Snippet:
bash
fruits=("Apple" "Banana" "Cherry")
Iterate using @ to get all elements
for item in "${fruits[@]}"
do
echo "Fruit: $item"
done
What are Associative Arrays? How do they differ from Indexed Arrays? Write a snippet to declare and access an associative array.
Associative Arrays:
Also known as key-value pairs or dictionaries (similar to HashMaps in Java/Python). Unlike indexed arrays, the keys are strings, not integers.
Difference from Indexed Arrays:
- Indexed: Keys are automatically generated integers ($0, 1, 2...$).
- Associative: Keys are user-defined strings (e.g., "name", "age").
- Requirement: Must be explicitly declared using
declare -Ain Bash v4+.
Snippet:
bash
1. Declaration (Mandatory)
declare -A user_info
2. Assignment
user_info[name]="John"
user_info[role]="Admin"
3. Accessing
echo "User {user_info[role]}"
Explain how User-Defined Functions are created in shell scripting. Discuss the scope of variables (local vs global) within functions.
Creating Functions:
Functions are blocks of code that can be reused. They must be defined before they are called.
Syntax:
bash
function_name () {
commands
}
OR
function function_name {
commands
}
Variable Scope:
- Global (Default): By default, all variables defined inside a function are global. If you change a variable inside a function, it changes in the main script too.
- Local: To restrict a variable to the function's scope, use the
localkeyword.
Example:
bash
func() {
local x=10 # Visible only here
y=20 # Visible globally
}
How are parameters passed to a user-defined function in a shell script? How does the function access these parameters?
Passing Parameters:
Parameters are passed to functions exactly like command-line arguments to a script—by listing them after the function name separated by spaces.
Call: my_function arg1 arg2
Accessing Parameters:
Inside the function, positional parameters are used:
$1: The first argument.$2: The second argument.$#: The number of arguments passed.$@: All arguments as a list.
Note: $0 inside a function still refers to the script's filename, not the function name.
Example:
bash
greet() {
echo "Hello, $1!"
}
greet "Alice" # Outputs: Hello, Alice!
Write a shell script that accepts a filename as a command-line argument and checks if it exists, is a file, or is a directory. It should also print the file permissions.
bash
!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
FILE=$1
if [ -e "$FILE" ]; then
echo "$FILE exists."
if [ -f "$FILE" ]; then
echo "It is a regular file."
elif [ -d "$FILE" ]; then
echo "It is a directory."
fi
# Display permissions
echo "Permissions: FILE | awk '{print $1}')"
else
echo "$FILE does not exist."
fi
Key Concepts:
$1: First argument.-e: Check existence.-f: Check if file.-d: Check if directory.ls -l: Used to retrieve permission string.
Explain the significance of the following Special Variables in shell scripting: ?, $#, and $@.
$0: The name of the script currently being executed.$?: The exit status of the last executed command.0usually means success, while non-zero indicates failure.$$: The Process ID (PID) of the current shell script. Useful for creating unique temporary filenames.$#: The count (number) of arguments passed to the script or function.- **
1" "$2" ...) when quoted, preserving whitespace within arguments.
Write a shell script to compute the Factorial of a number provided by the user using a while loop.
bash
!/bin/bash
echo "Enter a number:"
read num
fact=1
counter=$num
Check for negative input
if [ $num -lt 0 ]; then
echo "Factorial is not defined for negative numbers."
exit 1
fi
while [ $counter -gt 1 ]
do
fact=$((fact * counter))
counter=$((counter - 1))
done
echo "The factorial of fact"
Logic:
- Initialize
factto 1. - Loop while the counter (starting at
num) is greater than 1. - Multiply
factbycounterand decrementcounter. - Print the result.
Differentiate between Hard Quoting (Single Quotes) and Soft Quoting (Double Quotes) in shell scripting with examples.
1. Soft Quoting (Double Quotes " "):
- Preserves the literal value of most characters but allows substitution of variables (
$), backticks (command substitution), and escape characters (\). - Example:
bash
name="John"
echo "Hello $name" # Output: Hello John
2. Hard Quoting (Single Quotes ' '):
- Preserves the literal value of every character within the quotes. No substitution occurs.
- Example:
bash
name="John"
echo 'Hello name
Summary: Use double quotes when you need to interpolate variables; use single quotes when you want the string exactly as written.
Describe the Command Substitution mechanism. Compare the usage of backticks ` ` and $( ).
Command Substitution:
It allows the output of a command to replace the command itself. The shell executes the command and substitutes the standard output into the command line.
1. Backticks (`command`):
- The legacy syntax.
- Example:
DATE=\date`` - Drawback: Hard to nest and confusing to read (often mistaken for single quotes).
2. Dollar Parentheses ($(command)):
- The modern, preferred syntax.
- Example:
DATE=$(date) - Advantage: It allows easy nesting (
cmd1 (cmd3))) and is visually distinct.
Conclusion: $( ) is recommended over backticks for readability and nesting capabilities.
Write a shell script using a for loop to generate the Fibonacci series up to terms, where is input by the user.
bash
!/bin/bash
echo "Enter the number of terms:"
read N
a=0
b=1
echo "The Fibonacci series is:"
for (( i=0; i<N; i++ ))
do
echo -n "$a "
# Calculate next term
fn=$((a + b))
a=$b
b=$fn
done
echo "" # New line at end
Logic:
- Initialize
a=0,b=1. - Use a C-style
forloop running times. - Print
a. - Calculate sum
fn = a + b. - Update values:
abecomesb, andbbecomesfn.