Determine interpreter from inside script

穿精又带淫゛_ 提交于 2020-12-08 13:33:55

问题


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:

  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.



来源:https://stackoverflow.com/questions/11697076/determine-interpreter-from-inside-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!