从命令行检测Apple Silicon



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

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

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

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

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

当使用原生shell(比如/bin/bash -i/bin/zsh -i(时,Klas Mellbourn的答案会按预期工作。

如果使用通过Intel/Rosetta Homebrew安装安装的shell,则uname -p返回i386uname -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上使用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

/usr/bin/arch就是你所需要的。既然已经有一个程序可以为你做这件事,为什么还要把事情复杂化呢。

相关内容

  • 没有找到相关文章