Skip to main content

Bash

· 4 min read

Handling unset or empty variables

Syntax

  • + -- if the variable is set, use the substitution
  • - -- if the variable is not set, use the substitution
  • : -- handle empty string as though it were unset

Table

unset VARexport VAR=''export VAR='x'
echo ">${VAR+y}<"><>y<>y<
echo ">${VAR:+y}<"><><>y<
echo ">${VAR-y}<">y<><>x<
echo ">${VAR:-y}<">y<>y<>x<

When the variable is not set

$ unset VAR
$ echo ">${VAR+y}<"
><
$ echo ">${VAR:+y}<"
><
$ echo ">${VAR-y}<"
>y<
$ echo ">${VAR:-y}<"
>y<

When the variable is set to empty string

$ export VAR=''
$ echo ">${VAR+y}<"
>y<
$ echo ">${VAR:+y}<"
><
$ echo ">${VAR-y}<"
><
$ echo ">${VAR:-y}<"
>y<

When the variable is set to a non-empty string

$ export VAR='x'
$ echo ">${VAR+y}<"
>y<
$ echo ">${VAR:+y}<"
>y<
$ echo ">${VAR-y}<"
>x<
$ echo ">${VAR:-y}<"
>x<

(bash:unofficial-strict-mode)=

Unofficial "Strict Mode"

TL;DR

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

Explanation

  • set -e option - cease execution on first error
  • set -u option - treat undefined variables as an error
  • set -o pipefail option - treat an error in any sub-command within a pipeline as a failure of the whole pipeline

Colors Cheat Sheet

Regular Colors

ValueColor
\e[0;30mBlack
\e[0;31mRed
\e[0;32mGreen
\e[0;33mYellow
\e[0;34mBlue
\e[0;35mPurple
\e[0;36mCyan
\e[0;37mWhite

Bold

ValueColor
\e[1;30mBlack
\e[1;31mRed
\e[1;32mGreen
\e[1;33mYellow
\e[1;34mBlue
\e[1;35mPurple
\e[1;36mCyan
\e[1;37mWhite

Underline

ValueColor
\e[4;30mBlack
\e[4;31mRed
\e[4;32mGreen
\e[4;33mYellow
\e[4;34mBlue
\e[4;35mPurple
\e[4;36mCyan
\e[4;37mWhite

Background

ValueColor
\e[40mBlack
\e[41mRed
\e[42mGreen
\e[43mYellow
\e[44mBlue
\e[45mPurple
\e[46mCyan
\e[47mWhite

High Intensity

ValueColor
\e[0;90mBlack
\e[0;91mRed
\e[0;92mGreen
\e[0;93mYellow
\e[0;94mBlue
\e[0;95mPurple
\e[0;96mCyan
\e[0;97mWhite

Bold High Intensity

ValueColor
\e[1;90mBlack
\e[1;91mRed
\e[1;92mGreen
\e[1;93mYellow
\e[1;94mBlue
\e[1;95mPurple
\e[1;96mCyan
\e[1;97mWhite
===

High Intensity backgrounds

ValueColor
\e[0;100mBlack
\e[0;101mRed
\e[0;102mGreen
\e[0;103mYellow
\e[0;104mBlue
\e[0;105mPurple
\e[0;106mCyan
\e[0;107mWhite

Reset

ValueColor
\e[0mReset

References