Unit3 - Subjective Questions
CSC104 • Practice Questions with Detailed Answers
Explain the basic structure of a Bash script and the significance of the Shebang line.
Structure of a Bash Script
A Bash script typically consists of the following components:
- Shebang (Interpreter Directive): The very first line of the script.
- Comments: Lines starting with
#used to describe the code. - Commands: The actual Linux commands or control structures to be executed.
Significance of the Shebang (#!)
The Shebang is the character sequence #! followed by the absolute path to the interpreter that should execute the script.
- Syntax:
#!/bin/bash - Function: It tells the operating system's kernel which program (interpreter) to use to parse and execute the rest of the file. If omitted, the script may run in the current shell context, which can cause errors if the syntax differs (e.g., running Bash syntax in a C-shell).
- Portability: Using
#!/usr/bin/env bashis often preferred for portability as it locates the bash executable in the user's$PATH.
Define variables in Bash. How are they declared, and how can user input be stored in a variable?
Variables in Bash
A variable is a named storage location for data. Bash variables are untyped, meaning they are treated as strings by default but can be evaluated as numbers in arithmetic contexts.
Rules for Declaration:
- No spaces around the assignment operator
=. - Correct:
name="John" - Incorrect:
name = "John" - Variables are case-sensitive.
- To access the value, use the
name).
Storing User Input
The read command is used to take input from the user.
Syntax:
read [options] variable_name
Example:
bash
echo "Enter your name:"
read username
echo "Hello, $username"
-pflag: Allows prompting text on the same line. E.g.,read -p "Enter age: " age.-sflag: Hides input (useful for passwords).
What are Positional Parameters (Arguments) in Bash scripting? List the specific variables used to access them.
Positional Parameters are arguments passed to the script at the command line when it is invoked. They are accessed using special variables numbered based on their position.
Key Variables:
$0: The name of the script itself.9: The first through ninth arguments passed to the script.${10}: Arguments beyond 9 must be enclosed in curly braces.$#: The total count (number) of arguments passed.$@: Represents all arguments as separate strings.- *`$`**: Represents all arguments as a single string.
Example:
If running ./script.sh apple banana:
$0=./script.sh$1=apple$2=banana$#=2
Explain how to handle Arithmetic Operations in Bash using let, expr, and double parentheses.
Bash performs arithmetic operations primarily on integers. There are three common methods:
-
letCommand:- Used to evaluate arithmetic expressions on variables.
- Syntax:
let "result = num1 + num2" - Note: No spaces required inside quotes usually, but quoting is safe practice.
-
exprCommand:- An older method that evaluates expressions. It requires spaces between operators and operands.
- Syntax:
result=num1 + $num2) - Multiplication (
*) must be escaped (\*).
-
Double Parentheses
(( ... )):- The most modern and preferred method for integer arithmetic.
- Syntax:
result=$((num1 + num2))or just((num1++))for incrementing. - It supports C-style operators like
++,--,+=, etc. - Example:
$((x^2))calculates the square (25).
Describe the syntax for declaring and accessing Arrays in Bash.
Bash supports one-dimensional indexed arrays and associative arrays.
Declaration
- Direct Assignment:
fruits=("Apple" "Banana" "Cherry") - Index Assignment:
bash
fruits[0]="Apple"
fruits[1]="Banana"
Accessing Elements
- Single Element: Use curly braces and the index.
${fruits[1]}returns "Banana". - All Elements:
{fruits[*]}returns all items in the array. - Array Length:
${#fruits[@]}returns the count of elements. - String Length of an Element:
${#fruits[0]}returns the length of the string at index 0.
What is String Slicing (Substring Extraction) in Bash? Provide examples.
String Slicing allows you to extract specific parts of a string variable based on offset and length.
Syntax: ${string:position:length}
string: The variable containing the text.position: The starting index (0-based).length: (Optional) How many characters to extract.
Examples:
Assume text="Hello World"
-
Extract from start:
\rightarrow$ Output:Hello` -
Extract from offset to end:
\rightarrow$ Output:World` -
Extract last characters:
\rightarrow$ Output:World` (Note the space before -5).
Distinguish between File Test Operators and String Test Operators in conditional expressions.
Bash uses different flags within [ ] or [[ ]] to test files versus strings.
File Test Operators
Used to check properties of files and directories.
-e file: True if the file exists.-f file: True if it exists and is a regular file.-d file: True if it exists and is a directory.-r file: True if the file is readable.-w file: True if the file is writable.-x file: True if the file is executable.
String Test Operators
Used to compare text strings.
-z string: True if the string is empty (length is 0).-n string: True if the string is not empty.str1 = str2: True if strings are equal.str1 != str2: True if strings are not equal.
Explain the concept of 'Exit Status' in Bash. How is it checked?
Exit Status
Every command executed in Linux returns an integer value to the shell upon completion, known as the Exit Status or return code. This code indicates whether the command succeeded or failed.
- 0 (Zero): Indicates Success.
- Non-Zero (1-255): Indicates Failure (specific numbers often denote specific error types, e.g., 127 = command not found).
Checking Exit Status
The exit status of the last executed command is stored in the special variable $?.
Example:
bash
ls /non_existent_folder
echo $? # Output will likely be 2 (No such file)
ls /home
echo $? # Output will be 0 (Success)
It is crucial for flow control using if statements.
Describe the syntax and usage of the if-elif-else statement in Bash.
The if-elif-else statement allows the script to make decisions based on the exit status of commands or the result of test conditions.
Syntax
bash
if [ condition1 ]; then
Commands to run if condition1 is true
elif [ condition2 ]; then
Commands to run if condition2 is true
else
Commands to run if all conditions are false
fi
Key Components:
if: Starts the block.[ ... ]: The test command (alias fortest). Spaces inside the brackets are mandatory.then: Separates the condition from the commands.elif: (Optional) Stands for "else if".else: (Optional) Fallback commands.fi: Closes the conditional block (if spelled backwards).
Explain the case statement in Bash. When is it preferred over if-else?
The case statement is a control flow structure used to select a block of code to execute by matching a variable against a list of patterns.
Syntax
bash
case $variable in
pattern1)
command1
;;
pattern2)
command2
;;
*)
default_command
;;
esac
Components:
in: Key to start matching.): Ends the pattern definition.;;: Acts as a break (terminates the case option).- *`)`**: A wildcard pattern that acts as the "default" case if no other patterns match.
esac: Ends the case statement.
Preference:
case is preferred over if-else when checking a single variable against many specific values (e.g., menu selection or processing command flags), as it provides cleaner and more readable syntax.
Differentiate between while and until loops in Bash scripting.
Both while and until are conditional loops, but they operate on opposite logic regarding the exit code of the test command.
| Feature | While Loop | Until Loop |
|---|---|---|
| Logic | Executes as long as the condition is True (Exit status 0). | Executes as long as the condition is False (Exit status non-zero). |
| Termination | Stops when the condition becomes False. | Stops when the condition becomes True. |
| Syntax Keyword | while [ condition ] |
until [ condition ] |
| Use Case | "Keep doing this while x is valid." | "Keep doing this until x happens." |
Example (While): while [ $count -lt 5 ] runs while count < 5.
Example (Until): `until [ \ge$ 5.
Explain the two common syntax styles of the for loop in Bash: List-based and C-style.
1. List-based For Loop
This loops through a specific list of items (strings, filenames, numbers).
-
Syntax:
bash
for item in list
do
command $item
done -
Example:
for i in 1 2 3orfor file in *.txt. It iterates once for every item in the list.
2. C-style For Loop
This mimics the syntax used in C/C++/Java, primarily used for numerical iteration.
-
Syntax:
bash
for (( initialization; condition; increment ))
do
commands
done -
Example:
bash
for (( i=0; i<5; i++ ))
do
echo "Number $i"
doneThis allows for initialization, condition checking, and incrementing within the loop structure.
What are break and continue statements? How do they affect loop execution?
break and continue are loop control statements used to alter the flow of for, while, and until loops.
Break
- Function: Terminates the loop immediately. The control passes to the first command after the
donestatement. - Usage: Used to exit a loop prematurely when a specific condition is met (e.g., finding a file and stopping the search).
Continue
- Function: Skips the current iteration of the loop and jumps back to the condition check for the next iteration.
- Usage: Used to bypass specific items in a list without stopping the entire loop (e.g., processing all files except those ending in
.log).
How are Functions defined in Bash? How do you pass arguments to a function and access them?
Functions allow grouping commands into reusable blocks.
Definition Syntax
There are two ways to define a function:
function_name () { commands; }function name { commands; }
Passing Arguments
Arguments are not defined in the function parentheses like in C or Python. Instead, they are passed by writing them after the function name when calling it.
Call: my_func arg1 arg2
Accessing Arguments (Scope)
Inside the function, arguments are accessed using standard positional parameters:
$1: First argument passed to the function.$2: Second argument passed to the function.$@: All function arguments.
Note: These local positional parameters shadow the script's global command-line arguments while inside the function.
Discuss the various Debugging options available in Bash scripting.
Debugging helps identify errors in script execution. Bash provides modes that can be enabled via the command line or set command.
-
No-execute mode (
-n):- Usage:
bash -n script.sh - Function: Checks for syntax errors without actually running the commands. Useful for catching missing quotes or braces.
- Usage:
-
Verbose mode (
-v):- Usage:
bash -v script.sh - Function: Prints each command line to the screen as it is read (before execution).
- Usage:
-
X-trace / Debug mode (
-x):- Usage:
bash -x script.shorset -xinside the script. - Function: Prints the command and its arguments after expansion but before execution. It usually prefixes lines with
+. This is the most useful mode for logical errors.
- Usage:
-
Exit on Error (
-e):- Usage:
set -e - Function: Causes the script to exit immediately if any command returns a non-zero exit status.
- Usage:
What are Aliases in Bash? How can you make an alias persistent across system reboots?
Aliases
An alias is a shortcut for a command or a series of commands. It allows users to replace long or complex command strings with a shorter, custom name.
Syntax: alias name='command'
Example: alias ll='ls -la'
Persistence
Aliases defined in the terminal session are temporary and are lost when the terminal is closed.
To make them persistent:
- The alias definition must be added to the user's shell configuration file, typically
~/.bashrc(for Bash) or~/.bash_profile. - Steps:
- Open the file:
nano ~/.bashrc - Add the line:
alias update='sudo apt update && sudo apt upgrade' - Save and exit.
- Reload the file:
source ~/.bashrc
- Open the file:
Now the alias is available in every new terminal session.
Explain Command Chaining operators (&&, ||, ;) with examples.
Command chaining allows running multiple commands in a single line, with execution depending on the success of previous commands.
-
Semicolon (
;):- Logic: Run Command 1, then run Command 2, regardless of whether Command 1 succeeded or failed.
- Example:
date ; echo "Done"(Prints date, then prints "Done").
-
AND Operator (
&&):- Logic: Run Command 2 only if Command 1 succeeds (returns exit status 0).
- Example:
mkdir folder && cd folder(Only tries to enter the folder if creating it was successful).
-
OR Operator (
||):- Logic: Run Command 2 only if Command 1 fails (returns non-zero exit status).
- Example:
cat file.txt || touch file.txt(If reading the file fails, create it).
How can you create a Custom Command using a Bash script and make it executable from anywhere in the system?
To create a script that acts like a native system command (runnable from any directory without typing the full path), follow these steps:
-
Create the Script:
Write the script (e.g.,myscript.sh) and include the Shebang#!/bin/bash. -
Make it Executable:
Add execution permissions using chmod:
chmod +x myscript.sh -
Update the PATH:
The directory containing the script must be in the$PATHenvironment variable.- Option A (Move): Move the script to a directory already in the path, such as
/usr/local/bin(requires root).
sudo mv myscript.sh /usr/local/bin/myscript - Option B (Modify PATH): Add your custom script folder to the PATH in
~/.bashrc.
export PATH=$PATH:/path/to/my/scripts
- Option A (Move): Move the script to a directory already in the path, such as
Once done, you can type myscript in the terminal to run it.
Write a Bash script that takes a filename as an argument, checks if it exists, determines if it is a file or directory, and prints the result. If it doesn't exist, create it as a file.
Script:
bash
!/bin/bash
Check if an argument is provided
if [ $# -eq 0 ]; then
echo "Error: No filename provided."
exit 1
fi
FILENAME=$1
Check if the file/directory exists
if [ -e "$FILENAME" ]; then
echo "Path '$FILENAME' exists."
# Check type
if [ -f "$FILENAME" ]; then
echo "It is a regular file."
elif [ -d "$FILENAME" ]; then
echo "It is a directory."
else
echo "It is another type of file."
fi
else
echo "'$FILENAME' does not exist. Creating it now..."
touch "$FILENAME"
echo "File created successfully."
fi
Explanation:
$# -eq 0: Checks if user forgot the argument.-e: Checks existence.-f: Checks if it's a file.-d: Checks if it's a directory.touch: Creates the file if theelseblock is triggered.
Create a Menu-Driven Bash script using select or case and while loops that performs basic arithmetic operations (Add, Subtract, Multiply, Quit).
Script:
bash
!/bin/bash
while true; do
echo "================"
echo " CALCULATOR "
echo "================"
echo "1. Add"
echo "2. Subtract"
echo "3. Multiply"
echo "4. Quit"
read -p "Choose an option (1-4): " choice
# Exit condition
if [ "$choice" -eq 4 ]; then
echo "Exiting..."
break
fi
# Input numbers
read -p "Enter first number: " num1
read -p "Enter second number: " num2
case $choice in
1)
result=$((num1 + num2))
echo "Result: num2 = $result"
;;
2)
result=$((num1 - num2))
echo "Result: num2 = $result"
;;
3)
result=$((num1 * num2))
echo "Result: num2 = $result"
;;
*)
echo "Invalid option selected."
;;
esac
echo "" # Empty line for formatting
done
Explanation:
while true: Creates an infinite loop so the menu reappears after an operation.read: Captures user choice and numbers.case: Handles the logic based on the user's menu selection.$((...)): Performs the arithmetic.break: Exits the loop when option 4 is chosen.