shell 从命令行检测Apple Silicon

bqf10yzr  于 2023-04-21  发布在  Shell
关注(0)|答案(3)|浏览(169)

如何从shell脚本中检测到它正在M1 Apple硬件上运行?
我希望能够运行一个命令行命令,这样我就可以编写一个if-语句,该语句的主体只有在使用M1处理器的Mac上运行时才会执行(当然,至少是macOS Big Sur)。

ltqd579y

ltqd579y1#

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
xqk2d5yq

xqk2d5yq2#

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

更新:准备好Apple M1 ProApple M2Apple M2 Max等!

vhmi4jdf

vhmi4jdf3#

当使用原生shell(比如/bin/bash -i/bin/zsh -i)时,Klas Mellbourn'sanswer可以按预期工作。
如果使用通过Intel/Rosetta Homebrew安装的shell,则uname -p返回i386uname -m返回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

a duplicate question上的Jatin Mehrotra'sanswer详细介绍了如何获取特定的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

相关问题