【问题标题】:Versions of g++ called from zsh script and manually from terminal differ从 zsh 脚本调用和从终端手动调用的 g++ 版本不同
【发布时间】:2020-08-02 14:44:01
【问题描述】:

我最近在我的 MacOS 10.14.6 上安装了 g++-10 和 Homebew。我在.zshrc 文件中创建了一个别名:

alias g++="/usr/local/bin/g++-10"

为了在终端中自动编译和运行,我创建了一个.sh 文件。但是,我注意到从终端手动调用 g++ 时使用的 g++ 版本如下:

$ g++ --version
g++-10 (Homebrew GCC 10.2.0) 10.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这与从.sh 脚本调用 g++ 的不同。脚本displayg++Version.sh的内容是:

type g++
g++ --version

然后脚本调用的输出是:

g++ is /usr/bin/g++
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

这是以下命令的输出:

$ type g++
g++ is an alias for /usr/local/bin/g++-10

为什么两个版本不同?

【问题讨论】:

  • 为什么问题有bash标签?
  • @Cyrus 因为我使用了 bash 并且我的机器中仍然有一个 bash 配置文件,所以我不知道它是否相关。我在那里写了相同的别名。如果你愿意,我可以删除标签
  • type g++ 的输出添加到您的问题(无评论)。
  • @Cyrus。我只是按照你的要求写的
  • zsh 在你的脚本中使用你的alias 吗?

标签: bash shell terminal g++ zsh


【解决方案1】:

首先,除非明确启用,否则脚本中会忽略别名定义。您可以通过在脚本中执行 a 来打开它

setopt aliases

但不要忘记,这只会影响之后定义的别名,而不是之前定义的别名。

其次,除非明确启用,否则 zsh 脚本不会处理 .zshrc。从 zsh 手册页:

如果 shell 是交互式,则从 /etc/zshrc 和 ZDOTDIR/.zshrc 读取命令。

您可以通过使用-i 选项运行脚本来强制交互:

zsh -i your_script.zsh

如果您希望在您的 zsh 脚本中执行某个 g++ 版本,通常的解决方案是调整 PATH 以便 zsh 可以找到正确的版本。例如:

PATH=/your/path/to/g++:$PATH zsh your_script.zsh

如果你总是希望使用这个 g++ 版本,你当然会在你的 .zshrc 中相应地设置你的 PATH。由于您的命令 shell 是交互式的,因此 .zshrc 将被处理,并且由于 PATH 是一个环境变量,您的脚本将仔细阅读此 PATH,而无需您做任何特别的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多