从命令行检测 Apple Silicon

Detect Apple Silicon from command line

如何从 shell 脚本中检测到它 运行正在 M1 Apple 硬件上运行?

我希望能够 运行 一个命令行命令,这样我就可以编写一个 if 语句,其主体仅在 运行 时执行 mac 使用 M1 处理器(自然至少 macOS Big Sur)。

uname -m

将 return arm64 而不是 x86_64

if [[ $(uname -m) == 'arm64' ]]; then
  echo M1
fi

或者,正如@chepner 所建议的那样

uname -p

将 return arm 而不是 i386

if [[ $(uname -p) == 'arm' ]]; then
  echo M1
fi

另一个工具是 arch:

if [[ $(arch) == 'arm64' ]]; then
  echo M1
fi

当使用原生 shell 说 /bin/bash -i/bin/zsh -i 时,Klas Mellbourn's 按预期工作。

如果使用通过 Intel/Rosetta Homebrew 安装的 shell,则 uname -p returns i386uname -m returns x86_64,如 Datasun's .

所示

为了获得跨环境工作的东西(Apple Silicon Native、Rosetta Shell、Linux、Raspberry Pi 4s),我使用了 dorothy dotfile ecosystem 中的以下内容:

is-mac && test "$(get-arch)" = 'a64'

如果你没有使用dorothy,dorothy的相关代码是:

https://github.com/bevry/dorothy/blob/1c747c0fa6bb3e6c18cdc9bae17ab66c0603d788/commands/is-mac

test "$(uname -s)" = "Darwin"

https://github.com/bevry/dorothy/blob/1c747c0fa6bb3e6c18cdc9bae17ab66c0603d788/commands/get-arch

arch="$(uname -m)"  # -i is only linux, -m is linux and apple
if [[ "$arch" = x86_64* ]]; then
    if [[ "$(uname -a)" = *ARM64* ]]; then
        echo 'a64'
    else
        echo 'x64'
    fi
elif [[ "$arch" = i*86 ]]; then
    echo 'x32'
elif [[ "$arch" = arm* ]]; then
    echo 'a32'
elif test "$arch" = aarch64; then
    echo 'a64'
else
    exit 1
fi

Jatin Mehrotra's on 详细介绍了如何获取特定的 CPU 而不是架构。在我的 M1 Mac Mini 上使用 sysctl -n machdep.cpu.brand_string 输出 Apple M1,但是在 Raspberry Pi 4 Ubuntu 服务器上输出以下内容:

> sysctl -n machdep.cpu.brand_string
Command 'sysctl' is available in the following places
 * /sbin/sysctl
 * /usr/sbin/sysctl
The command could not be located because '/sbin:/usr/sbin' is not included in the PATH environment variable.
This is most likely caused by the lack of administrative privileges associated with your user account.
sysctl: command not found

> sudo sysctl -n machdep.cpu.brand_string
sysctl: cannot stat /proc/sys/machdep/cpu/brand_string: No such file or directory

我发现 sysctl -n machdep.cpu.brand_string 报告了 Apple M1 即使进程是 运行 在 Rosetta 下。