views:

38

answers:

1

How would you exit-gracefully-upon-entry when invoking a .sh script from anything other than bash?

Of course bash-isms like the following don't work in csh and the like so you get an error rather than the intended error message:

if [ ${BASH_VERSION-not_running_within_bash} = not_running_within_bash ]; then                                                                                                                                                       
  echo This script is meant to be executed by the Bash shell but it isn\'t.
  echo Continuing from another shell may lead to unpredictable results.
  echo Execution will be aborted... now.
  # ... Real message has a screenful of info about the network ...
  return
fi

I am looking for a solid header to prepend to a series of scripts that may potentially be run by (very) heterogeneous machines and I am concerned about things like "ps listing may have a different syntax on a different machine", "different behaviour upon encountering unbound variables", "bash being run from /opt/local/bin/bash on Macs", "missing tools on some machines, e.g. pidof", different variable expansion rules (i.e. $var Vs ${var}), etc.

+4  A: 

Make the script executable and prepend:

#!/usr/bin/env bash
Ignacio Vazquez-Abrams
In a system without bash installed at all (but with sh, csh, ksh, and all the rest) this does not print the intended error message?
Maroloccio
It will complain that bash can't be found. If you want something more general-purpose or specific than that then you'll have to build your own binary that can be distributed.
Ignacio Vazquez-Abrams