Skip to content

Instantly share code, notes, and snippets.

@duxsco
Last active May 8, 2022 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duxsco/fad211d5828e09d0391f018834f955c9 to your computer and use it in GitHub Desktop.
Save duxsco/fad211d5828e09d0391f018834f955c9 to your computer and use it in GitHub Desktop.
Prevent "tainting" Bash script variables via environment

I decided to use following convention for variables in my Bash scripts:

A) Variables are written without curly brackets if:

  • They are fine to be set via environment, e.g. $HOME
  • The environment doesn't play a role, e.g. $OPTARG whose value is set by getopts

B) All other variables are written with curly brackets, e.g.: ${KERNEL_VERSION}

Variables that fall under scenario B) are unset at the beginning of the Bash script.

The space separated list of variables to be unset can be given out the following way:

PATH_TO_SCRIPT="./path/to/script.sh"
grep -v "^[[:space:]]*#" "$PATH_TO_SCRIPT" | grep -o '${[^0-9][^}]*}' | sed 's/${\([^}]*\)}/\1/' | sed -e 's/^\([!#]\)//' -e 's/^\([a-zA-Z_][a-zA-Z_]*[a-zA-Z0-9_]*\).*/\1/' | sort -u | paste -d" " -s -

To check whether variables without curly brackets are used you can do:

PATH_TO_SCRIPT="./path/to/script.sh"
grep --color '$[^{^(]' "${PATH_TO_SCRIPT}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment