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 )

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)