Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. It has been distributed widely as the default login shell for most UNIX based systems. The shell's name is an acronym for Bourne-again shell.

Bash is often confused with the terminal. This is incorrect. Bash is a scripting language and a type of shell, a terminal is the program you use to interact with your shell.

Shebang

The default shell that ships with most UNIX systems is bash. You are however free to pick your shell.

That is why it is important that in the bash code you write, you make sure to add a shebang. Other shells (like zsh or sh) may not include some bash features or have different syntax.

By adding a shebang we force our shell to to interpret the code as bash and use the shell set in the shebang.

Never write a script without adding a shebang. The best shebang to add is the first one in the list below since it uses the bash shell defined in your environment since you can have multiple bash instances (confusing right?)

#! /usr/bin/env bash
# 1. Interpret as: bash, using the bash version defined for our terminal (e.g homebrew bash instead of macos bash)

#! /usr/bin/bash
# 2. Intepret as: bash, using the bash version at /usr/bin/bash (BSD bash on macOS, GNU bash on linux)

#! /usr/bin/python
# 3. Intepret as: python, using the python version at /usr/bin/python (stock Python distribution)

Running/interpreting bash code

There are two ways of running bash code. The simplest way will be the way you are probably already using: launching a terminal and typing in commands. Lets take a simple example and go over it:


Another way of using bash is by writing a script and evaluating that code as bash. Bash is a very powerful scripting language since it runs directly in your shell and can do almost anything you desire or do in the terminal. Bash script do not require any file extension, any plaintext file can be used as a bash script. It is however common to use the .sh extension, this helps certain programs better recognise the file as a shell script.

There are multiple ways of calling a script from your shell. You can either use the bash executable to run it trough the interpreter or invoke the script directly in the shell. Invoking a script directly is the most common way of calling a script, but requires your script to be executable:

Bash scripts are evaluated from top to bottom sequentially. Keep this in mind because code at the top of scripts will be run before any function calls below.

Expressions

In bash you can call expressions directly on your shell using square bracket notation. This square bracket notation is an alias of bash's test command and will evaluate the expression in brackets.

In the wild, you will see both [ and [[ being used. They both work roughly the same way but differ in some usage scenarios: