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 bygetopts
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}"