在bash中重命名单个脚本的可执行文件

时间:2017-04-12 17:59:25

标签: linux bash shell

我想运行shell脚本,其中exe1被查找为/path/to/exe1,而是引用我在exe2中看到的/path/to/exe2。理想情况下,我想以最紧凑的方式做到这一点,副作用最小。

为了使这个例子具体,有点类似于我实际关心的问题,我有一个shell脚本script.sh其中

$ cat script.sh
#!/usr/bin/env bash
python --version

我当前PATH上有两个可执行文件:

$ python --version
Python 2.7.x
$ python3 --version
Python 3.5.x

我想以这样的方式致电script.sh

$ <magic> ./script.sh
Python 3.5.x
$ python --version
Python 2.7.x

到目前为止我能找到的最佳解决方案是

$ mkdir /tmp/python3 && ln -s $(which python3) /tmp/python3/python && env PATH="/tmp/python3:$PATH" ./script.sh

通过使用mktemp -d并清理它可以做得更好,但它仍然涉及编写大多数不必要的文件,因为看起来我应该只能告诉bash,将python视为python3。像别名这样的东西是理想的,但它们不会传递到子壳上。是否有一个我缺少的明显工具,或者我是否坚持使用此方法的变体?

1 个答案:

答案 0 :(得分:1)

  

我想以这样的方式调用script.sh

$ <magic> ./script.sh
Python 3.5.x
$ python --version
Python 2.7.x

您可以使用以下功能执行此操作:

(python() { python3 "$@"; }; declare -xf python; ./script.sh)
  • 我们在子shell中创建一个名为python的函数,只调用python3可执行文件。
  • 在子shell中执行此操作,以便不会弄乱当前环境。