Bash, which stands for Bourne Again SHell, is a widely used command-line interpreter and scripting language that was originally developed by Brian Fox for the GNU Project as a free replacement for the Bourne shell (sh). Bash combines the features of the Bourne shell with many enhancements and new features, making it a powerful and flexible tool for users and system administrators.

Before you start your first script, you need to understand the shebang(#!) character.

What does #! Mean?

The #! sequence, known as “shebang,” is a special character combination used at the beginning of script files in Unix-like operating systems. It tells the system which interpreter should be used to execute the script.

When you place #! at the top of a script file followed by the path to an interpreter (e.g., #!/bin/bash), it instructs the operating system to use the specified interpreter to run the script. This helps ensure that the script runs with the correct interpreter, regardless of the user’s environment or default shell.

Here’s how a typical shebang line looks:

1
#!/usr/bin/env python3

In this example, #!/usr/bin/env python3 indicates that the script should be executed using Python 3, with env being used to locate the Python interpreter in the user’s environment.

Writing a Simple Bash Script

To create a simple Bash script, follow these steps:

  1. Create a new file:

    1
    touch hello_world.sh
  2. Make the script executable:

    1
    chmod +x hello_world.sh
  3. Edit the script (using nano, vim, or another text editor):

    1
    nano hello_world.sh
  4. Add the shebang and commands:

    1
    2
    #!/bin/bash
    echo "Hello, World!"
  5. Run the script(**sh hello_world.sh**, **bash hello_world.sh**, or **./hello_world.sh**):

    1
    2
    $ sh hello_world.sh
    Hello, World!

    or

    1
    2
    $ bash hello_world.sh
    Hello, World!

    or

    1
    2
    $ ./hello_world.sh
    Hello, World!

If you see the error -bash: . /hello_world.sh: Permission denied when running the script with . /hello_world.sh, it means the script doesn’t have execute permissions. To fix this, use the following commands to set the execute permission, then try running the script again.

1
2
3
$ chmod +x ./hello_world.sh
$ ./hello_world.sh
Hello, World!