gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:26 25 4
gpt4 key购买 nike

我想运行 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com