Introduction to Bash

Introduction to Bash#

Bash is a Unix shell and command language as free software replacement for the Bourne shell. With this tutorial, you will learn how to use Bash to your advantage and be more depth than the short introduction for end-users.

$ bash --version
GNU bash, version 5.1.4(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Hello world in Bash#
1#!/bin/bash
2echo Hello World

The file extension .sh is used to indicate that the file is a shell script, but doesn’t give it extra abilities. To execute it the file must be run with the bash command.

$ bash script.sh

The script above will print the text Hello World to the console. It can also be executed directly as a command when the execute bit has been set on the file. This ability depends on the operating system that supports the hashbang line that tells which command to execute and feed the content to it.

Run scripts directly as a command#
S chmod +x script.sh
$ ./script.sh

Now that the script can be executed the debugging features of Bash are available. The -x option will enable debugging features when the script is executed. The following command will print the command that is being executed and the content of the script.

Debugging Bash scripts#
$ bash -x script.sh

The -x can also be passed as an option to the bash command in the hashbang.

Hello world in Bash with debugging enabled#
1#!/bin/bash -x
2echo Hello World

As third option it is also possible to enable or disable the debugging features with -x to enable it and +x to disable it again.

Debugging features both enabled and disabled#
1#!/bin/bash
2set -x
3echo Hello World
4set +x
5echo Hello World

Bash by default tries to continue when errors occur, but it is possible to stop the script when a command fails by using the set -e command or execute the script with the -e option. If we add the option to our Hello World script, then nothing will happen for now as the script is correct.

Hello world in Bash with error handling enabled#
1#!/bin/bash
2set -e
3echo Hello World

In the modified script, we have added the -e option, which will cause the script to exit when an error occurs. And we made an error as the script is not correct.

Hello world in Bash with error handling enabled#
1#!/bin/bash
2set -e
3ech0 Hello World