问题
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.
回答1:
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
回答2:
This could be an option, depending on how you launch the script:
- Install bash 4.2 as
/opt/userwriteablefolder/bin/bash
. - Use '#!/usr/bin/env bash' as the shebang in your script.
- Add '/opt/userwriteablefolder/bin' to the front of
PATH
in the environment from which your script is called, so that thebash
there will be used if present, otherwise the regularbash
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.
来源:https://stackoverflow.com/questions/11697076/determine-interpreter-from-inside-script