Getting Started with Bash Script

As previously explained, a simple text editor can be used to write Batch Script, although slightly more advanced editors offer the advantage of syntax highlighting, which can make the process easier.

Bash Script, contained in text files with a '.sh' file extension, run in a terminal window.

Below is a simple example of a Bash Script, which displays the message, 'Hello World', to the screen.

#!/bin/bash

# Display 'Hello World' message.
echo Hello World

In the example above, the '#!' is known as a shebang and is followed by the path to the bash interpreter, which is used to execute the script. Any line thereafter that starts with a '#' symbol is a comment and allow for explanatory text to be included. Finally, the 'echo' command ensures that the text that follows is displayed in the terminal window.

It is also possible to include comments over multiple lines.

#!/bin/bash

: 'This
is
a
multi
line 
comment'

echo This script contains a multi line comment

The multi line comment starts with a colon, followed by a space, then a single quote. Another single quote should appear at the end of the comment.

Before being able to run a Bash Script, it is likely that execution privileges will need to be granted, as by default, even the creator of the file will only have read and write permissions. This can be done using the 'chmod' command.

chmod 744 demo.sh

Here, the creator of the file, demo.sh, is given read, write and execute permissions, whilst everyone else has read permissions only.

Once this is done the script can be run from the command line.

./demo.sh

The './' means look for the file in the current directory. To run a script in a different directory, the path would need to be specified.

/path/to/file/demo.sh