Page cover image

Bash Scripting Basics

Bash scripting is a powerful way to automate tasks in Linux by combining multiple commands into a single executable file. Bash scripts can streamline repetitive actions, schedule tasks, and even perform complex workflows automatically. Here’s an expanded guide to creating and running a basic Bash script:


1. Create a Script File with .sh Extension

The first step is to create a new file for your script. While you can name a script file anything, adding the .sh extension is a helpful convention that identifies it as a shell script.

  • Example:

    $ nano myscript.sh

    This command opens a new file called myscript.sh in the Nano editor. You could also use vim or any other text editor to create and edit the script.


2. Start the Script with #!/bin/bash

The line #!/bin/bash at the beginning of the script is known as a shebang. It tells the system that this file should be executed using the Bash shell. Without this line, the system may not recognize the file as a Bash script or may try to run it with a different shell, leading to unexpected errors.

  • Example:

    #!/bin/bash

    Adding #!/bin/bash as the first line is essential for making sure the script runs in Bash. This line also allows the script to be run directly without explicitly calling bash.


3. Add Commands Line by Line

After the shebang, add each command you want to run in the script, one command per line. Each line represents an action that the script will execute sequentially. For example:

#!/bin/bash
echo "Hello, this is my first script!"

In this script:

  • echo "Hello, this is my first script!" outputs text to the terminal. echo is a Bash command that displays whatever is inside the quotes. This is just one example; you can include any commands in your script, from file manipulation to complex loops.

  • Adding More Commands: You can add multiple commands to perform a sequence of actions. For instance:

    #!/bin/bash
    echo "Starting the backup process..."
    mkdir /backup
    cp /home/user/documents/* /backup
    echo "Backup complete."

This script creates a directory (/backup), copies all files from /home/user/documents to that directory, and confirms completion with a message. You can customize the commands based on your specific automation needs.


4. Make the Script Executable

For a script to be run directly from the terminal, it needs to have executable permissions. Use the chmod command to grant execution rights:

  • Example:

    $ chmod +x myscript.sh

The +x option adds executable permissions to myscript.sh, allowing you to run it like a standard command. Without this step, you’d have to use bash myscript.sh to run the script, even with a shebang line.


5. Run the Script

To execute the script, navigate to the directory containing the script and run it by prefixing it with ./:

  • Example:

    $ ./myscript.sh

The ./ indicates that the script is located in the current directory. When you run ./myscript.sh, each command in the script is executed in sequence, just as if you had typed them manually in the terminal.


A Basic Example Script

Here’s a full example of a simple script, complete with comments to explain each step. Comments are added with # and are ignored by the shell, which is helpful for making the script easier to understand and maintain:

#!/bin/bash
# This script performs a simple greeting and shows the current date and time.

echo "Hello, this is my first script!"
echo "The current date and time are:"
date
echo "This script has completed."

Explanation:

  • #!/bin/bash specifies Bash as the interpreter.

  • echo "Hello, this is my first script!" displays a greeting message.

  • date shows the current date and time.

  • echo "This script has completed." confirms the script has finished running.


Adding Variables to Scripts

Bash scripts can use variables to store data temporarily and make the script more dynamic:

  • Example with Variables:

    #!/bin/bash
    NAME="Alice"
    echo "Hello, $NAME! Welcome to your Bash script."

In this script, NAME is a variable that stores the string "Alice". By using $NAME, you can reference the variable’s value. This can be useful for setting file paths, dates, or other values that may change.


Using Arguments in Scripts

Bash scripts can accept arguments from the command line, making them even more flexible. Arguments are passed after the script name, and can be accessed with special variables like $1, $2, etc.

  • Example with Arguments:

    #!/bin/bash
    echo "Hello, $1! You passed the argument: $2"

Running ./myscript.sh Alice "How are you?" would produce:

Hello, Alice! You passed the argument: How are you?

Arguments allow the script to accept user input dynamically.


Creating a Script with Loops and Conditionals

To automate more complex tasks, you can add control structures like loops and conditionals:

  • Example with Conditional Statements:

    #!/bin/bash
    if [ "$1" == "start" ]; then
        echo "Starting the process..."
    elif [ "$1" == "stop" ]; then
        echo "Stopping the process..."
    else
        echo "Please specify 'start' or 'stop'."
    fi

This script checks if the first argument is "start" or "stop" and prints an appropriate message. It’s useful for handling different actions based on input.

  • Example with Loops:

    #!/bin/bash
    for i in {1..5}; do
        echo "This is loop number $i"
    done

This script uses a for loop to print "This is loop number X" five times, where X is the loop count. Loops can automate repetitive tasks like monitoring or periodic backups.


Summary of Bash Script Workflow

  1. Create a file with a .sh extension.

  2. Start with #!/bin/bash to specify Bash as the interpreter.

  3. Add Commands line by line.

  4. Make Executable using chmod +x filename.sh.

  5. Run the Script using ./filename.sh.

Last updated

Was this helpful?