BASH Tutorial: Hello World

Tech Articles
Next
This tutorial covers introductory BASH shell scripting for people with a little familiarity with UNIX/Linux.
BASH Scripting Introduction

Assumptions
This tutorial assumes only that you 
  • are  using a UNIX-like operating system 
    • with BASH installed 
    • the examples assume it is installed as /bin/bash
  • know how to create and edit files
  • have some exposure to chmod

Use which bash to confirm that BASH is installed, you should see something like:
$ which bash
/bin/bash

Create a file called hello1.sh with the following content.

#!/bin/bash
echo "Hello World"

Give the file execute permissions:
chmod 755 hello1.sh
or
chmod +rx hello1.sh


run the script:

$ ./hello1.sh
Hello World

Explanation
#! are the first two characters in a shell script and identify the interpreter. These two characters are sometimes called “shebang”.
/bin/bash defines the path and name of the interpreter
echo will print to standard out (usually the screen)


Hello World with Command Line Input

I prefer to make copies of tutorial scripts in case I want to revisit the skills I learned.  For example:
cp hello1.sh hello2.sh

replace World with $1 in your script. It should look like this:

#!/bin/bash
echo "Hello $1"

Run it:
$ ./hello2.sh Pete
Hello Pete

Explanation

The name Pete in the command is called “an argument” that is passed to the script.

The $1 is a variable for the first argument on the command line after your scipt’s name. This is referred to as a  a positional parameter. $2 will be the second and so on.

Many scripts will provide information about what arguments the script is expecting. The following script is a simple example of this.




Hello World with usage information and if statement

Edit your scipt so that it looks like:

#!/bin/bash
if [ -z $1 ]
then
      echo "usage: $0 followed by a name"
else
      echo "Hello $1"
fi


Explanation

The conditional [ -z $1 ] checks to see if an argument was passed. Specifically, the -z is true if $1 is null (has a length of 0).

The else clause allows for an alternate set of commands to be run when the conditional is false.

The positional parameter $0 is the script’s name.


Using if/then/elif/else

Edit your scipt so that it looks like the example, below. The new lines are underlined

#!/bin/bash
if [ -z $1 ]
then
            echo "usage: $0 followed by a name"
elif [ $1 = Pete ]
            then
            echo "Hello $1, welcome back!"
else
            echo "Hello $1"
fi

Explanation

The elif clause allows you add additional conditionals to test when the original are false. More than one elif clause can be used. In other words, when the if conditional is false, it tries the first elif and when that is false, checks the following elif and if all the elif conditionals are false runs the statements in the else clause.



Suggestions for Future Learning