Skip to content

3. Bash

1. Getting Started

Bash (Bourne Again Shell) is a Unix shell and command language that is widely used in Linux and macOS systems for automating tasks and running scripts. Here’s how to get started with Bash on Ubuntu or any Linux system.


1.1 Check if Bash is Installed

Most Linux distributions, including Ubuntu, come with Bash pre-installed. You can check your current shell by running:

Terminal window
echo $SHELL

If the output is /bin/bash, then Bash is installed and set as your default shell. To verify the version of Bash installed, run:

Terminal window
bash --version

1.2 Writing and Running Your First Bash Script

a. Create a New Bash Script

  1. Open a terminal.

  2. Create a new file called hello.sh using any text editor (like nano or vim):

    Terminal window
    nano hello.sh
  3. Write the following Bash code in the file:

    #!/bin/bash
    echo "Hello, World!"
    • #!/bin/bash is called the “shebang” and tells the system that this script should be run using the Bash shell.
    • echo is a built-in command that outputs text to the terminal.
  4. Save and exit the text editor.

b. Make the Script Executable

Before you can run the script, you need to give it execute permissions:

Terminal window
chmod +x hello.sh

c. Run the Script

Now, you can execute your Bash script:

Terminal window
./hello.sh

You should see the output: Hello, World!

1.3 Common Bash Commands

Here are some frequently used Bash commands:

  • ls: Lists files and directories in the current directory.

    Terminal window
    ls
  • cd: Changes the current directory.

    Terminal window
    cd /path/to/directory
  • pwd: Prints the current working directory.

    Terminal window
    pwd
  • touch: Creates a new, empty file.

    Terminal window
    touch newfile.txt
  • cat: Displays the contents of a file.

    Terminal window
    cat hello.sh
  • cp: Copies files or directories.

    Terminal window
    cp source.txt destination.txt
  • mv: Moves or renames files or directories.

    Terminal window
    mv oldname.txt newname.txt
  • rm: Removes files or directories.

    Terminal window
    rm file.txt

2. Control Structures in Bash

Control structures in Bash help manage the flow of execution in a script.

2.1 Conditional Statements

  • if, elif, else: These are used for conditional execution of code.

    Terminal window
    # Basic if-else structure
    if [ condition ]; then
    # Commands to run if condition is true
    echo "Condition is true"
    elif [ another_condition ]; then
    # Commands if another condition is true
    echo "Another condition is true"
    else
    # Commands to run if all conditions are false
    echo "Condition is false"
    fi
  • Example:

    Terminal window
    age=18
    if [ $age -ge 18 ]; then
    echo "You are an adult."
    else
    echo "You are a minor."
    fi
    • -ge stands for “greater than or equal to.” Common conditional operators include:
      • -eq: Equal
      • -ne: Not equal
      • -lt: Less than
      • -le: Less than or equal to
      • -gt: Greater than
      • -ge: Greater than or equal to

2.2 Case Statement

  • A case statement is used to handle multiple conditions more cleanly than multiple if-else branches.

    Terminal window
    case $variable in
    pattern1)
    # Commands if variable matches pattern1
    ;;
    pattern2)
    # Commands if variable matches pattern2
    ;;
    *)
    # Default commands if no pattern is matched
    ;;
    esac
  • Example:

    Terminal window
    day="Monday"
    case $day in
    "Monday")
    echo "Start of the work week!"
    ;;
    "Friday")
    echo "It's almost weekend!"
    ;;
    *)
    echo "Just another day."
    ;;
    esac

2.3 Loops

Bash supports different types of loops to iterate over a set of commands.

  • for loop: Iterate over a list or a range of values.

    Terminal window
    for item in list; do
    # Commands to execute
    echo $item
    done
    • Example:

      Terminal window
      for num in {1..5}; do
      echo "Number: $num"
      done

      This loop iterates from 1 to 5, printing each number.

  • while loop: Repeat commands while a condition is true.

    Terminal window
    while [ condition ]; do
    # Commands to execute
    done
    • Example:

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

      This loop continues as long as count is less than or equal to 5.

  • until loop: The opposite of while; it runs until a condition becomes true.

    Terminal window
    until [ condition ]; do
    # Commands to execute
    done
    • Example:

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

2.4 Loop Control Statements

  • break: Exit the loop early.

    Terminal window
    for i in {1..10}; do
    if [ $i -eq 5 ]; then
    break
    fi
    echo "Number: $i"
    done
  • continue: Skip to the next iteration of the loop.

    Terminal window
    for i in {1..5}; do
    if [ $i -eq 3 ]; then
    continue
    fi
    echo "Number: $i"
    done

2. Data Structures in Bash

Bash doesn’t have built-in advanced data structures like arrays or dictionaries found in higher-level programming languages, but you can simulate them using basic constructs.

2.1 Variables

  • Variables in Bash are simple containers for storing data (strings, integers, etc.). They are dynamically typed and do not require type declaration.

    Terminal window
    name="Alice"
    age=25
    • Access the value of a variable using $.
      Terminal window
      echo "Name: $name"

2.2 Arrays

  • Bash supports one-dimensional arrays.

    Terminal window
    # Declare an array
    fruits=("apple" "banana" "cherry")
    # Access array elements (index starts at 0)
    echo ${fruits[0]} # Outputs: apple
    # Access all elements
    echo ${fruits[@]}
    # Add a new element to the array
    fruits+=("orange")
    # Get the number of elements in the array
    echo ${#fruits[@]} # Outputs: 4
    • Iterating over arrays:

      Terminal window
      for fruit in "${fruits[@]}"; do
      echo $fruit
      done

2.3 Associative Arrays (Hash Maps)

  • Bash version 4.0 and later supports associative arrays, which allow you to use strings as keys.

    Terminal window
    # Declare an associative array
    declare -A person
    # Assign values
    person[name]="Alice"
    person[age]=25
    person[city]="New York"
    # Access values
    echo ${person[name]} # Outputs: Alice
    # Iterate over keys and values
    for key in "${!person[@]}"; do
    echo "$key: ${person[$key]}"
    done

2.4 Strings

  • Strings are a basic data type in Bash and are easy to manipulate.

    Terminal window
    greeting="Hello"
    name="Alice"
    message="$greeting, $name!"
    echo $message # Outputs: Hello, Alice!
    • String Length:

      Terminal window
      echo ${#name} # Outputs: 5 (length of "Alice")
    • Substring Extraction:

      Terminal window
      echo ${name:1:3} # Outputs: "lic" (substring from index 1, length 3)
    • Concatenation:

      Terminal window
      full_name="$greeting, $name"

2.5 File Descriptors

  • Bash allows working with input, output, and error streams using file descriptors.

    • Redirect output to a file:

      Terminal window
      echo "Hello" > output.txt
    • Redirect errors to a file:

      Terminal window
      command 2> error.log
    • Pipe commands:

      Terminal window
      ls | grep ".txt"