Unit 3 - Notes

CSC104

Unit 3: Bash Scripting Fundamentals

1. Introduction to Bash Scripting

Bash (Bourne Again SHell) is a command language interpreter for the GNU operating system. It allows users to execute commands from a text file, essentially automating tasks that would otherwise be typed manually into the terminal.

  • Role: Acts as the interface between the user and the kernel.
  • Utility: Used for system administration, task automation, file manipulation, and complex operational logic.
  • Interpreter: Reads the script line-by-line and executes the commands.

2. Structure and Hello World

Every Bash script follows a specific structure to ensure the system recognizes how to execute it.

The Shebang (#!)

The first line of a script must define the interpreter.

  • Syntax: #!/bin/bash
  • Purpose: Tells the system to use the Bash executable located in /bin to parse the rest of the file.

Execution Permissions

By default, created files are not executable.

  • Command: chmod +x scriptname.sh
  • Running the script: ./scriptname.sh or bash scriptname.sh

Example: Hello World

BASH
#!/bin/bash
echo "Hello, World!"


3. Comments

Comments are non-executable lines used for documentation.

  • Single-line comment: Starts with #.
  • Multi-line comment: While not natively supported, a workaround is using Here-Docs.

BASH
# This is a single line comment

: '
This is a multi-line comment
block often used for
documentation.
'


4. Variables

Variables store data for processing. Bash variables are untyped (treated as strings unless context implies otherwise).

Declaration and Usage

  • Syntax: VARIABLE_NAME="Value" (No spaces around the =).
  • Accessing: Use the VARIABLE_NAME or ${VARIABLE_NAME}).

Command Substitution

Storing the output of a command into a variable.

BASH
CURRENT_DATE=$(date)
# OR
CURRENT_USER=`whoami`


5. User Input

Interactive scripts often require input from the user during execution.

  • Command: read
  • Flags:
    • -p: Display a prompt.
    • -s: Silent mode (hides input, useful for passwords).

BASH
read -p "Enter your username: " USERNAME
read -s -p "Enter your password: " PASSWORD
echo "Welcome, $USERNAME"


6. Arguments (Positional Parameters)

Scripts can accept inputs directly from the command line when executed.

  • $0: Name of the script itself.
  • $1: First argument passed.
  • $2: Second argument passed.
  • $#: Total number of arguments.
  • $@: All arguments passed as a list.

Example execution: ./script.sh apple banana
Inside script: 2 is "banana".


7. Arrays and String Slicing

Arrays

Variables that hold multiple values.

  • Definition: fruits=("apple" "banana" "cherry")
  • Access Element: echo ${fruits[0]} (Output: apple)
  • All Elements: echo ${fruits[@]}
  • Array Length: echo ${#fruits[@]}

String Slicing

Extracting parts of a string.

  • Syntax: ${string:start:length}

BASH
text="LinuxScripting"
slice=${text:0:5}  # Extracts "Linux"


8. Exit Status

Every command returns an exit code upon completion.

  • 0: Success.
  • 1-255: Error/Failure.
  • Checking Status: Use $? immediately after a command.

BASH
ls /non_existent_folder
echo $?
# Output will be non-zero (usually 2 for ls error)


9. Conditional Expressions

Bash uses test commands [ ... ] or the extended [[ ... ]] to evaluate conditions.

Arithmetic Operators

  • -eq: Equal to
  • -ne: Not equal to
  • -gt: Greater than
  • -lt: Less than
  • -ge: Greater than or equal to
  • -le: Less than or equal to

String Operators

  • =: Equal to
  • !=: Not equal to
  • -z: String is null (length zero)
  • -n: String is not null

File Operators

  • -f: File exists and is a regular file.
  • -d: Directory exists.
  • -e: File/directory exists.
  • -x: File is executable.

10. Control Flow: If-Else

Used to execute code blocks based on conditions.

BASH
if [ "$1" -gt 10 ]; then
    echo "Number is greater than 10."
elif [ "$1" -eq 10 ]; then
    echo "Number is exactly 10."
else
    echo "Number is less than 10."
fi


11. Control Flow: Switch-Case

Useful when checking a variable against multiple specific patterns.

BASH
case "$1" in
    start)
        echo "Starting service..."
        ;;
    stop)
        echo "Stopping service..."
        ;;
    restart)
        echo "Restarting..."
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac


12. Loops

Loops allow code to be executed repeatedly.

For Loop

Iterates over a list or a range.

BASH
# C-style
for ((i=1; i<=5; i++)); do
    echo "Count: $i"
done

# Range style
for name in Alice Bob Charlie; do
    echo "Hello $name"
done

While Loop

Executes as long as the condition is true.

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

Until Loop

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

BASH
until [ $count -gt 5 ]; do
    # code
done

Loop Control

  • break: Exits the loop immediately.
  • continue: Skips the rest of the current iteration and jumps to the next one.

13. Functions

Blocks of reusable code.

  • Syntax:
    BASH
    function_name() {
        local var_name="Local Scope"  # 'local' keeps variable inside function
        echo "Argument 1: $1"         # Arguments are passed like script args
    }
    
    # Calling the function
    function_name "TestParam"
    

14. Debugging

Techniques to identify errors in scripts.

  • Verbose Mode: Run script with bash -x script.sh. This prints every command before executing it.
  • Syntax Check: bash -n script.sh. Checks for syntax errors without executing.
  • Inside Script:
    • set -x: Turn debugging on.
    • set +x: Turn debugging off.

15. Shortcuts

Keyboard shortcuts to speed up terminal interaction.

  • Tab: Auto-complete file or command names.
  • Ctrl + C: Terminate running command (SIGINT).
  • Ctrl + Z: Suspend running command.
  • Ctrl + A: Go to start of line.
  • Ctrl + E: Go to end of line.
  • Ctrl + R: Search command history.
  • !!: Re-run the previous command.
  • !$: Repeats the last argument of the previous command.

16. Aliases

Shortcuts for long commands.

  • Creating Alias: alias update='sudo apt update && sudo apt upgrade'
  • Removing Alias: unalias update
  • Listing Aliases: alias

17. Custom Commands and Persistent Changes

To make scripts, variables, or aliases permanent across reboots.

The .bashrc File

  • Located in the user's home directory (~/.bashrc).
  • Runs every time a new terminal session is opened.
  • Process:
    1. Open file: nano ~/.bashrc
    2. Add alias or variable: alias ll='ls -alF'
    3. Save and exit.
    4. Reload: source ~/.bashrc

Adding to PATH

To run a script from anywhere without typing the full path:

  1. Create a bin directory: mkdir ~/bin
  2. Add to .bashrc: export PATH="PATH"
  3. Move script to ~/bin and make executable.

18. Basic Script Creation (Capstone Example)

A sample script combining multiple concepts: A simple system report.

BASH
#!/bin/bash

# Define variables
DATE=$(date)
HOSTNAME=$(hostname)

echo "--- System Report for $HOSTNAME ---"
echo "Date/Time: $DATE"
echo "-----------------------------------"

# Check if user is root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root for full details."
  exit 1
fi

# Disk Usage
echo "Disk Usage:"
df -h | grep "^/dev/"
echo ""

# Active Users
echo "Logged in users:"
who
echo "-----------------------------------"
echo "Report Complete."