Coding Hello World in Bash

Here’s a basic Hello World in Bash that includes a simple function such that it could be sourced from your .bashrc.

But First …

Step by Step

Navigate using cd to a place to create your Bash files. Usually this will be your $HOME/repos/codebook directory.

cd
cd repos/codebook

💬 Remember that cd with no arguments just takes you home.

Now make a directory for your Bash scripts and change into it.

mkdir bash
cd bash
pwd
/home/rob/repos/codebook/bash

Notice that there is nothing in here (as expected).

ls

Nothing. Good.

Now let’s touch a file to create it.

touch hello
ls -l
-rw-r--r-- 1 rob rob 0 May 17 19:07 hello

Notice that those permissions don’t have any x in them. That will be something we deal with later. For now, this is just a readable and writable text file like any other.

Let’s open it up and edit it. Use vi hello or code -r . depending on your preference.

Now add the following simple echo statement.

echo hello world

Notice you don’t need anything but hello and world. This is a special way that echo makes it really easy to print stuff out to the terminal command line.

Now let’s run it.

Exit your editor or open another terminal.

bash hello
hello world

You might be wondering why bash is needed. Our text file hello is just a text file. We need to make it into a script.

To do this we first have to change the permission mode on the file. Here’s how. The ls -l will show us the changes.

chmod +x hello
ls -l hello
-rwxr-xr-x 1 rob rob 18 May 17 19:56 hello

Notice the xs in everything.

Maybe you also noticed that the color of the file changed, this is because you terminal is help you out by showing you scripts and programs that can be executed.

Now that it has execute permission you can just run it without bash in front. But we still have to indicate we want to run this script right here. That is what the ./ means.

./hello

You should see it work.

There’s one last thing we should always do for scripts. It’s called the shebang line.

Open your script up again and add the following to the first line. Put a blank line for good style.

#!/bin/bash

echo hello world

Now close and run it again.

Congratulations you have written your first Bash script!