28

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

我希望能够运行一个命令行命令,这样我就可以编写一个if语句,其主体只有在具有 M1 处理器的 Mac 上运行时才会被执行(当然至少是 macOS Big Sur)。

4

3 回答 3

35
uname -m

将返回arm64而不是x86_64

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

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

uname -p

将返回arm而不是i386

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

另一个工具是arch

if [[ $(arch) == 'arm64' ]]; then
  echo M1
fi
于 2020-12-11T22:15:28.043 回答
8

我发现即使该过程在 Rosetta 下运行,也会sysctl -n machdep.cpu.brand_string报告。Apple M1

于 2021-11-05T12:11:04.690 回答
5

使用本机外壳说/bin/bash -ior/bin/zsh -i时,Klas Mellbourn 的 答案按预期工作。

如果使用通过 Intel/Rosetta Homebrew 安装的 shell,则uname -p返回i386,然后uname -m返回x86_64,如Datasun 的 评论所示。


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

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重复问题的回答详细介绍了如何获取特定 CPU 而不是体系结构。在我的 M1 Mac Mini 上使用输出,但是在 Raspberry Pi 4 Ubuntu 服务器上输出以下内容:sysctl -n machdep.cpu.brand_stringApple M1

> 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
于 2021-06-27T07:02:55.127 回答