Skip to content

Bash

Bash is the GNU Project's shell—the Bourne Again SHell. This is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and the C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard. It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification.1

Examples

Get Script Location1

Simple example
SCRIPT_DIR=$(readlink -f $(dirname "${BASH_SOURCE[0]}"))
Complex example
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

Comparisons

Comparisons

Single-bracket [ ... ] (the POSIX test) and double-bracket [[ ... ]] (the Bash conditional) look similar but behave differently. Use [ ... ] for portability; prefer [[ ... ]] in Bash scripts for safer and more powerful conditionals.

  • [ ] is the traditional POSIX test (often a shell builtin). It is portable to /bin/sh, requires careful quoting of expansions to avoid word-splitting and pathname expansion, and supports standard file- and string-test operators (e.g. -z, -n, -f, -eq, =/!=). Operators like < and > must be quoted or escaped because the shell may treat them as redirections.

  • [[ ]] is a Bash (and ksh) keyword that provides extended conditional features: no word-splitting or pathname expansion on unquoted expansions (so variable tests are safer without always needing quotes), pattern matching with == (glob-style) and =~ (regular-expression), and the ability to use && / || and parentheses inside the conditional. It is not POSIX portable, so avoid it when you need a script to run under plain /bin/sh.

  • Compound Commands

  • Conditional Expressions

Check for Environment Variable

if [[ ! -v $MY_VAR ]]; then
    echo "MY_VAR is not defined."
else
    echo "MY_VAR is defined."
fi

Essentially checks for an empty string

if [ -z "${MY_VAR}" ]; then
    echo "MY_VAR is not defined."
else
    echo "MY_VAR is defined."
fi

Check Script Arguments

if [[ "$#" -eq 0 ]]; then
    echo "No arguments provided."
    exit 1
else
    echo "The script received the following arguments:"
    for arg in "$@"; do
        echo "- $arg"
    done
fi

Terminal Colors

tput commands
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BOLD=$(tput bold)
REVERSE=$(tput rev)
RESET=$(tput sgr0)