Drobot Viktor
Drobot Viktor

Reputation: 363

Reliable way to require only bash shell in script

I wonder if there are any reliable methods (cross-shell compatible) to require bash as shell interpreter for my script.

For example, I have shell script that can be run only with bash interpreter. Despite of #!/usr/bin/bash at the beginning of my script some smart user/hacker can run it directly with another shell: $ csh script.sh This can lead to unwanted consequences.

I already thought about testing echo $0 output and exiting with error code but syntax for if statements (as long as for another conditional statements) is different among various shell interpreters. Testing directly for $BASH_VERSION variable is unreliable due to the same limitations.

Are there any cross-shell compatible and reliable way to determine current interpreter? Thank you!

EDIT: as for now I have the following basic check for compatibility:

### error codes
E_NOTABASH=1
E_OLD_BASH=2

# perform some checks
if [ -z "$BASH_VERSION" ]
then
    echo -e "ERROR: this script support only BASH interpreter! Exiting" >&2
    exit $E_NOTABASH
fi

if [[ "${BASH_VERSINFO[0]}" -lt 4 ]]
then
    echo -e "ERROR: this script needs BASH 4.0 or greater! Your current version is $BASH_VERSION. Exiting" >&2
    exit $E_OLD_BASH
fi

Upvotes: 1

Views: 170

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15418

Not entirely sure I understand the scope of the question.

A #! /usr/bin/env bash shebang will fail if there's no bash, but to keep it from being explicitly parsed by another shell, um...

How about -

case "$BASH_VERSION" in
  4.*) : bash version 4+ so ok ;;
    *) echo "please run only with bash v4+. Aborting."
       exit 1                  ;;
esac

If the syntax works, it is either right or hacked.

If it crashes, you're good. :)

Upvotes: 3

pyr0
pyr0

Reputation: 377

you could check for the parent process id, command respectively

pstree -p $$ | grep -m 1 -oE '^[^\(]+'

or

ps $(ps -o ppid=$$)

Upvotes: 1

Related Questions