In this tutorial, we learn how to create and run a simple Bash script which prints out “Hello World”.

What is Shebang (#!)

Every shell script starts with the Shebang #! symbols. This is declared at the first line of the script and basically tells the shell which interpreter will be used to run the script.

#!/bin/bash
...

Hello World Bash Script

Now, we’re going to create a bash script that prints out the words “Hello World” in a terminal.

First create a file called hello_world.sh. Using the terminal we write:

$ touch hello_world.sh

Our file is now created.

Next, open the file in your favorite editor; I’m using nano, so it would be:

$ nano hello_world.sh

Once the hello_world.sh is open in your editor, type in the following commands:

#!/bin/bash

echo "Hello World"

Execute Shell Script

Now to print out the hello world, we need to execute the shell script we created.

There are a number of ways to execute the shell script

$ sh ./hello_world.sh ## incorrect
$ ./hello_world.sh ## correct
$ bash ./hello_world.sh ## correct

The first method is incorrect, because you are telling the shell to use the shell interpreter not the bash interpreter.

The second method is correct because we just run the script which will use the defined interpreter in the file, the first line in the script which is #!/bin/bash.

The third method is also correct because in this case, we are saying to use the bash interpreter which is the same as the one defined in the file.

Permission Denied When Executing Shell Script

If you try to run your script using:

$ ./hello_world.sh

-bash: ./hello_world.sh: Permission denied

you will see a permissions denied error. This is because the script doesn’t have execute permission.

You can grant the script an execute permission by using:

$ chmod +x ./hello_world.sh

Now, if you run the script again, you will see the “Hello World” printed out:

$ ./hello_world.sh

Hello World
#linux #bash