从 zsh 脚本调用和从终端手动调用的 g++ 版本不同

Versions of g++ called from zsh script and manually from terminal differ

我最近在我的 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

为什么两个版本不同?

首先,别名定义在脚本中被忽略,除非明确启用。您可以通过在脚本中执行 a

来打开它
setopt aliases

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

其次,除非明确启用,否则 .zshrc 不会由 zsh 脚本处理。来自 zsh man-page:

If the shell is interactive, commands are read from /etc/zshrc and then ZDOTDIR/.zshrc.

您可以通过 运行 您的脚本与 -i 选项强制交互:

zsh -i your_script.zsh

如果你想在你的zsh脚本中执行某个g++版本,通常的解决办法是调整PATH以便zsh可以找到正确的版本。例如:

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

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