Dangerous Shell Scripts

I’ve seen a few shell scripts recently which use environment variables to determine installation paths etc so that the script Just Works when run.

This is generally desirable but the importance of checking the environment variables before doing anything should not be overlooked. Consider the following (admittedly contrived!) example:

#!/usr/bin/env bash

# uninstall product
PRODUCTROOT="${INSTALLROOT}/${PRODUCTNAME}"

rm -rf "${PRODUCTROOT}"

The script assumes INSTALLROOT and PRODUCTNAME are set but it doesn’t verify this. If they’re not, the effective behaviour is:

rm -rf "/"

(Please don’t try that out!)

While it’s not possible for a deletion script to really know whether or not you meant to delete something, it can at least check the preconditions.

To check that the necessary variables are set:

#!/usr/bin/env bash

function check_env_vars() {
  local var_list=$@
  for var_name in ${var_list[@]}; do
    eval var_value="\$$var_name"
    if [ -z "${var_value}" ]; then
      echo "${var_name} must be set!" >&2
      exit 1
    fi
  done
}

check_env_vars INSTALLROOT PRODUCTNAME

# if we get this far, the variables are set
# you could change the exit to return an error status
# instead and trap it here

2 Responses to “Dangerous Shell Scripts”

  1. TERRY says:


    Pillspot.org. Canadian Health&Care.Best quality drugs.Special Internet Prices.No prescription online pharmacy. No prescription drugs. Order drugs online

    Buy:Prozac.Zocor.Ventolin.SleepWell.Aricept.Lasix.Nymphomax.Buspar.Female Pink Viagra.Lipitor.Amoxicillin.Benicar.Advair.Acomplia.Wellbutrin SR.Cozaar.Female Cialis.Seroquel.Lipothin.Zetia….

  2. ALEJANDRO says:


    PillSpot.org. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.Best quality drugs. Online Pharmacy. Order pills online

    Buy:Viagra Soft Tabs.Viagra Professional.Viagra Super Active+.Cialis.Tramadol.Soma.Super Active ED Pack.Cialis Soft Tabs.Viagra.Levitra.Cialis Professional.Viagra Super Force.VPXL.Propecia.Maxaman.Cialis Super Active+.Zithromax….

Leave a Reply