从脚本内部确定解释器 [英] Determine interpreter from inside script

查看:52
本文介绍了从脚本内部确定解释器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个剧本;它需要使用bash的关联数组(相信我的那个).

它需要在普通计算机以及具有/bin/bash 3.2的某些其他计算机上运行.

如果我将解释器声明为/opt/userwriteablefolder/bin/bash4 ,即我放置在其中的bash 4.2的位置,则工作正常./p>

我想在脚本的开头进行测试,以检查解释外壳是什么,如果它是bash3.2,则调用 bash4 $ 0 $ @ .问题是我无法找出任何方法来确定解释外壳是什么.我真的希望不做基于$ HOSTNAME的决定,但这会在必要时起作用(这也很尴尬,因为它需要传递我们已经完成了此操作"标志).

出于几个原因,仅具有两个脚本"不是一个好的解决方案.

解决方案

您可以通过查看 $ SHELL 来检查使用哪个解释器,其中包含shell可执行文件的完整路径(例如/bin/bash )

然后,如果它是Bash,则可以通过多种方式检查Bash版本:

  • $ {BASH_VERSINFO [*]} -版本组件的数组,例如((4 1 5 1发行版x86_64-pc-linux-gnu)
  • $ {BASH_VERSION} -字符串版本,例如 4.1.5(1)-发布
  • 当然还有"$ 0" --version

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.

解决方案

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

这篇关于从脚本内部确定解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆