Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine interpreter from inside script

I have a script; it needs to use bash's associative arrays (trust me on that one).

It needs to run on normal machines, as well as a certain additional machine that has /bin/bash 3.2.

It works fine if I declare the interpreter to be /opt/userwriteablefolder/bin/bash4, the location of bash 4.2 that I put there.. but it then only works on that machine.

I would like to have a test at the beginning of my script that checks what the interpreting shell is, and if it's bash3.2, calls bash4 $0 $@. The problem is that I can't figure out any way to determine what the interpreting shell is. I would really rather not do a $HOSTNAME based decision, but that will work if necessary (It's also awkward, because it needs to pass a "we've done this already" flag).

For a couple reasons, "Just have two scripts" is not a good solution.

like image 660
zebediah49 Avatar asked Oct 08 '22 02:10

zebediah49


2 Answers

You can check which interpreter is used by looking at $SHELL, which contains the full path to the shell executable (ex. /bin/bash)

Then, if it is Bash, you can check the Bash version in various ways:

  • ${BASH_VERSINFO[*]} -- an array of version components, e.g. (4 1 5 1 release x86_64-pc-linux-gnu)
  • ${BASH_VERSION} -- a string version, e.g. 4.1.5(1)-release
  • And of course, "$0" --version
like image 107
ephemient Avatar answered Oct 13 '22 11:10

ephemient


This could be an option, depending on how you launch the script:

  1. Install bash 4.2 as /opt/userwriteablefolder/bin/bash.
  2. Use '#!/usr/bin/env bash' as the shebang in your script.
  3. Add '/opt/userwriteablefolder/bin' to the front of PATH in the environment from which your script is called, so that the bash there will be used if present, otherwise the regular bash will be used.

The benefit would be to avoid having to detect the version of bash at runtime, but I realize your setup may not make step 3 desirable.

like image 21
chepner Avatar answered Oct 13 '22 10:10

chepner