If a Shell Script is not POSIX Compliant and a specific Non-POSIX Shell Functionality is being used (e.g. local in Bash), It may arises some errors and unintended actions if that script is interpreted by a POSIX Compliant shell like sh or dash
The same applies if the script implement some functionality that is specific of the shell for which it is being created
Therefore, It’s necessary to perform some checks at the beginning of the script to prevent above problems
Shell Check
POSIX Compliant
foo(){ case $( /bin/ps -p "$PPID" -o comm= ) in *bash) return 0 ;; *) printf "Shell not allowed. Exiting...\n" 1>&2 return 1 ;; esac}
INFO
Above code extracts the executed command which created the Script’s Parent Process
If It is not run by a Bash, returns false. Thus, can be chained with →
$ foo || exit 99 # Script exits with a 99 Error code if not a Bash
It’s POSIX Compliant since only a case statement is used with Command Substitution and Standard Globbing
Note that It’s not necessary to quote that expansion as case statement’s parameter is one of the fews situations which not undergoes Word Splitting and Globbing
CAUTION
Be aware that this check must be performed before any other one, as It checks the shell that should run the script
Bash Version Check
It can be done through BASH_VERSION escalar parameter and BASH_VERSINFO indexed array