如何从一个shell脚本中检测它是否正在运行M1苹果硬件上?
我想运行一个命令行命令,以便编写一个if语句,只有在使用M1处理器的Mac(自然是至少macOS Big Sur)上运行时才执行其主体。
如何从一个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” ]]
。 - bheinzsysctl -n machdep.cpu.brand_string
是最好的命令。 - Maziyar我发现即使在 Rosetta 下运行,sysctl -n machdep.cpu.brand_string
仍然报告了 Apple M1
。
更新:准备好迎接 Apple M1 Pro
、Apple M2
、Apple M2 Max
等等!
arch -arm64 bash
的方式离开这里”的必要条件。难以置信arch
没有-l
来列出当前可用的机器架构。 - JoeApple M2 Max
。 - Klas Mellbourn/bin/bash -i
或/bin/zsh -i
,Klas Mellbourn的answer将按预期工作。uname -p
返回i386
,uname -m
返回x86_64
,如Datasun的comment所示。
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
sysctl -n machdep.cpu.brand_string
输出Apple M1
,但在树莓派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
uname -m
返回 x86_64
,我认为你可能是通过 Rosetta 运行终端。你是否在终端程序的“获取信息”对话框中检查了“使用 Rosetta 打开”? - Klas Mellbourn/bin/bash -i
,然后运行 uname -m
,它会返回 arm64
,而 uname -p
返回 arm
,这是由于我的默认 shell 是通过 rosetta 运行的,该 shell 是由 homebrew 安装的。感谢您帮助我找到问题所在。我已更新了解答。 - balupton
uname -p
可能会给你想要的信息,但我没有 M1 进行测试。 - chepner