Shell Scripting Tutorial: Hello World

This is the very first in a completely unplanned series: bash shell scripting tutorial. It’s been quite some time since my first contact with bash shell. Since then, I’ve fallen in love with the language. Quite literally, if I may add. From simple to complex maintenance scripts to parallel activities to libraries, I’ve fiddled some.

This series is my humble way of saying thanks to all stackoverflow posts and to Julio Cesar Neves, who wrote the best programming book I’ve ever read. Seriously. These tutorials are also a thank you to an old friend who once taught my very first scripting lesson:

Shell scripting is about piecing together very small programs that do next to nothing on their own but become very very powerful when (spoiler) pipe’d together.

Except, maybe, for find. Find deserves a tutorial series on its own. But that’s for another day.

First Contact

So, without further ado, please do open your favourite tutorial and type in the following:

#! /bin/bash

echo “Hello, World!”

And save it. You don’t have to use the “.sh” extension, though it’s quite popular.

To run it, cd into the directory you saved the file and issue this command:

$ cd /home/user/bash-tutorial/001-hello

$ bash hello.sh

Hello, World!

$ ./hello.sh

-bash: ./hello.sh: Permission denied

Ouch. What happened?

First you started bash directly. For your script to run the second time round, it must have the execute permission. Try this instead:

$ chmod u+x hello.sh

$ ./hello.sh

Hello, World!

Basic Shell Script Structure

Shebang

This simple 2-liner consists of two lines. The first one is commonly known as “shebang” and instructs your OS program loader on how to execute your program since it is basically a text file.

You can use this line to pass parameters to your interpreter. The most commonly used are “-l”, which starts a new login session with a fresh environment, and “-x”, which enables debugging mode. “-e” is also very useful and is used to interrupt the script if any program it executes exits with a status other than zero.

Echo, echo, echo…

The second line tells the interpreter to write whatever is between the quotes on the standard output. In this case, it’s the quintessential message “Hello, World!”. For the time being, the standard output will be the console.


If you have any questions, please do leave a comment bellow. Don’t forget to like and share. Until next time!

Leave a comment