Unit 2 - Notes

CSE325 4 min read

Unit 2: Shell Scripting

This unit covers the fundamental concepts of shell scripting in a Linux environment using the Bash (Bourne Again SHell) interpreter.

1. Script Creation, Execution, and Permissions

A shell script is a text file containing a sequence of commands for a UNIX-based operating system. It allows for the automation of repetitive tasks.

The Shebang Line

Every shell script should begin with a "shebang" line. This tells the system which interpreter to use to execute the file.

BASH
#!/bin/bash

Creating and Executing a Script

  1. Create the file: Use a text editor (vi, nano, gedit).
    BASH
        nano myscript.sh
        
  2. Execution Methods:
    • Direct execution (requires execute permission): ./myscript.sh
    • Using the interpreter explicitly: bash myscript.sh or sh myscript.sh

File Permissions

Linux uses a permission system (Read-r, Write-w, Execute-x) for three categories of users: Owner (u), Group (g), and Others (o). By default, created files are usually not executable.

To change permissions, use chmod (Change Mode).

Symbolic Mode:

BASH
chmod +x script.sh      # Add execute permission for everyone
chmod u+x script.sh     # Add execute permission for the user (owner) only
chmod 755 script.sh     # rwx for owner, rx for group and others

A diagram illustrating the Linux File Permission structure. The visual should show a breakdown of th...
AI-generated image — may contain inaccuracies


2. Environment and User-Defined Variables

Variables in shell scripting are loosely typed (essentially treated as strings).

User-Defined Variables

  • Syntax: VARIABLE_NAME=value (No spaces around the =).
  • Access: Use the VARIABLE_NAME).
  • Best Practice: Use uppercase for constants/environment variables, lowercase for local variables.

BASH
name="John Doe"
age=25
echo "My name is $name and I am $age years old."

Reading User Input

The read command captures input from standard input (keyboard).

BASH
echo "Enter your username:"
read username
echo "Hello, $username"

Environment Variables

These are system-wide variables available to all child processes.

  • $HOME: Path to user's home directory.
  • $PATH: Directories the shell searches for executable commands.
  • $USER: Current logged-in user.
  • $SHELL: Path to the current shell.

To make a user variable an environment variable, use export:

BASH
export MY_VAR="Global Data"


3. Arithmetic Operations using expr and bc

Bash treats variables as strings by default. Specific tools are needed for math.

The expr Command

Used for integer arithmetic. Spaces are mandatory between operators and operands.

  • Syntax: expr op1 operator op2
  • Multiplication: The * must be escaped with a backslash \*.

BASH
a=10
b=20
sum=`expr $a + $b`    # Backticks for command substitution
mul=$(expr $a \* $b)  # $() syntax (preferred)
echo "Sum: $sum, Product: $mul"

The bc Command (Basic Calculator)

Used for floating-point arithmetic (decimals), which expr cannot handle. It is often used with pipes.

  • scale: Defines the number of decimal places.

BASH
a=10.5
b=2
result=$(echo "scale=2; $a / $b" | bc)
echo "Result: $result"

Double Parentheses ((...))

Bash built-in for C-style integer arithmetic (no spaces required).

BASH
((sum = a + b))
((cnt++))


4. Input/Output Redirection and Pipes

Linux treats everything as a file. There are three standard streams:

  1. STDIN (0): Standard Input (Keyboard).
  2. STDOUT (1): Standard Output (Screen/Terminal).
  3. STDERR (2): Standard Error (Screen/Terminal).

Redirection Operators

  • > : Output Redirection. Overwrites the file.
    BASH
        ls > filelist.txt
        
  • >> : Append Redirection. Adds to the end of the file.
    BASH
        date >> logfile.txt
        
  • < : Input Redirection. Feeds file content to a command.
    BASH
        wc -l < filelist.txt
        
  • 2> : Error Redirection. Redirects error messages.

Pipes (|)

Pipes connect the STDOUT of the first command to the STDIN of the second command.

BASH
# List files, then count lines
ls -l | wc -l

A conceptual block diagram illustrating Input/Output Redirection and Pipes. On the left, a box label...
AI-generated image — may contain inaccuracies


5. Conditional Statements and Menu-Driven Programs

if-else Statements

Used to make decisions based on the exit status of commands or test conditions.

Syntax:

BASH
if [ condition ]; then
    # statements
elif [ condition ]; then
    # statements
else
    # statements
fi

Common Test Operators:

  • Integers: -eq (equal), -ne (not equal), -gt (greater than), -lt (less than).
  • Strings: = (equal), != (not equal), -z (empty string).
  • Files: -f (file exists), -d (directory exists), -r (readable).

case Statement (Switch)

Ideal for menu-driven programs.

BASH
echo "1. Show Date"
echo "2. List Files"
read choice

case $choice in
    1) date ;;
    2) ls -l ;;
    *) echo "Invalid option" ;;
esac


6. Looping Constructs

for Loop

Iterates over a list of items or a range.

List Syntax:

BASH
for i in 1 2 3 4 5
do
   echo "Number: $i"
done

C-Style Syntax:

BASH
for (( i=0; i<5; i++ ))
do
   echo "Counter: $i"
done

while Loop

Executes as long as the condition is true.

BASH
count=1
while [ $count -le 5 ]
do
    echo "Count: $count"
    ((count++))
done

until Loop

Executes as long as the condition is false (until it becomes true).

BASH
count=1
until [ $count -gt 5 ]
do
    echo "Count: $count"
    ((count++))
done

A comparative flowchart diagram showing the logic of 'While' loop vs 'Until' loop side-by-side. Left...
AI-generated image — may contain inaccuracies


7. Indexed and Associative Arrays

Bash supports one-dimensional arrays.

Indexed Arrays (Numeric Keys)

  • Declaration: arr=(value1 value2 value3)
  • Access Single Element: ${arr[index]} (Index starts at 0)
  • Access All Elements: ${arr[@]}
  • Array Length: ${#arr[@]}

BASH
fruits=("Apple" "Banana" "Cherry")
echo ${fruits[1]}       # Output: Banana
echo ${fruits[@]}       # Output: Apple Banana Cherry

Associative Arrays (String Keys)

Requires explicit declaration using declare -A (Available in Bash 4.0+).

BASH
declare -A user_info
user_info[name]="Alice"
user_info[role]="Admin"

echo "User ${user_info[name]} is an ${user_info[role]}"


8. User-Defined Functions and Parameter Passing

Functions allow you to group commands into a logical block for reuse.

Defining and Calling Functions

BASH
# Definition
function greet() {
    echo "Hello, World!"
}

# Calling the function
greet

Parameter Passing

Arguments passed to a function are accessed using positional parameters (2, etc.), similar to script arguments.

  • $0: Script name (not function name).
  • 9: First to ninth arguments.
  • $#: Total number of arguments.
  • $@: All arguments as a list.

BASH
add_numbers() {
    sum=$(($1 + $2))
    echo "Sum is: $sum"
}

# Calling with parameters
add_numbers 10 20

Return Values

  • Exit Status: return n (0-255). Checked via $?.
  • Output: echo "result" inside the function, captured via command substitution.

A visualization of the "Positional Parameters" concept in memory when executing a script with argume...
AI-generated image — may contain inaccuracies
. Use a clean computer science memory structure diagram style with arrows connecting the variable names to their values.]