linux - 在 bash 中为单个脚本重命名可执行文件

标签 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.别名之类的东西是理想的,但它们不会传递给子 shell 。是否缺少一个明显的工具,或者我是否坚持使用此方法的变体?

最佳答案

I want to call script.sh in such a way that

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

你可以使用一个函数来做到这一点:

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

关于linux - 在 bash 中为单个脚本重命名可执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43376539/

相关文章:

c - 后台进程和挂起进程 - 在 C 中实现作业控制 Shell

java - 提取 tar 文件时无效的用户/用户组

linux - 在 linux du 上删除点和斜杠

linux - 如何恢复被覆盖的 bash 配置文件

bash - 在 bash 脚本中捕获 mysqldump 错误

linux - 在命令行中将 TSV 文件合并在一起

c - 如何更改 tcsetattr() 的 Linux 中断定时器

linux - 如何更新终端上特定行的文本?

bash - bash 中的动态 case 语句

linux - 根据文件夹结构删除旧目录