2017-04-12 139 views
1

我想运行shell脚本,其中exe1改为查找为/path/to/exe1而不是引用我在/path/to/exe2中看到的exe2。理想情况下,我想以最紧凑的方式做到这一点,副作用最小。在bash中重命名单个脚本的可执行文件

为了使这个例子具体,有点类似于我真正关心的问题,我有一个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。像别名一样是理想的,但它们不会被传递到子壳体上。有没有一个明显的工具我错过了,或者我坚持使用这种方法的变种?

+0

所以你想运行这个脚本,并且根据你在脚本之外做的事情,能够让它访问那个时候你想要的任何版本的python?也就是说,“今天我需要Python 3,所以doas3 ./script.sh”?使用参数运行脚本并确定要运行的内容是否可以接受?也就是“./script.sh -p 3”,然后脚本就会说“if -p 3,use python3,else python2”? –

回答

1

我想打电话给script.sh以这样的方式

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

您可以使用函数做这样的:

(python() { python3 "[email protected]"; }; declare -xf python; ./script.sh) 
  • 我们在只调用01的子shell中创建名为python的函数可执行文件。
  • 在子外壳中执行此操作,以便当前环境不会混乱。