如何在 Swift 脚本中获取 Zsh 别名命令的输出?

How to get the output of Zsh's alias command in Swift script?

为了在 macOS 上使用 Zsh,我在 ~/.zshrc 添加了很多自己的别名。
我发现我可以使用 alias 命令来显示注册的别名。

% alias
myalias1='cd ...'
myalias2='cp ...'
myalias3='mv ...'
myalias4='find ...'
...

我想在 Swift 脚本中使用它,所以我创建了以下程序。
然而,虽然 pwdls 命令被正确执行,但 alias 命令没有输出任何东西。

// shell.swift
import Foundation

@discardableResult
func shell(_ args: String...) -> Int32 {
  let task = Process()
  task.launchPath = "/usr/bin/env"
  task.arguments = args
  task.launch()
  task.waitUntilExit()
  return task.terminationStatus
}

print("--- run pwd command:")
shell("pwd")

print("--- run ls command:")
shell("ls")

print("--- run alias command:")
shell("alias")
% swift shell.swift
--- run pwd command:
/Users/myname
--- run ls command:
Applications  Documents     Library     Music       Public
Desktop       Downloads     Movies      Pictures    shell.swift
--- run alias command:

我无法理解其原因。
如果有解决办法请告诉我。

谢谢。

(我是用翻译工具问这个问题的。)

zsh中,如果你运行which alias,你会得到alias: shell built-in command。虽然在 /usr/bin/alias 确实存在一个真正的可执行文件,但当您 运行 在 zsh 中执行 alias 命令时,它不是 运行 的代码。它内置于 zsh 本身。

您可以通过 运行ning /usr/bin/env alias 重新创建您的 Swift 代码正在做的事情。就我而言,我得到一个空输出。

您需要做的是将您的 Swift 代码编辑为 运行 zsh,并在 [=10= 内编辑为 运行 alias ].相当于/bin/zsh -l -c "alias".

尝试运行宁shell("zsh", "-l", "-c", "alias")