自作のスクリプトが、macOS と RPi の両方で使えるようにハードウェアを判断する必要があったのですが、「bash mac 検出
」を Qiita 記事に絞ってググっても出てこなかったので、自分のスニペット用の備忘録。
TL;DR
#!/bin/bash
is_mac () {
sw_vers > /dev/null 2>&1
return $?
}
is_pi () {
#cat /proc/cpuinfo | grep "^model name\s*:\s*ARMv" 2>&1 > /dev/null
grep --quiet "^model name\s*:\s*ARMv" /proc/cpuinfo 2>&1 > /dev/null
return $?
}
if is_mac ; then
echo 'Is mac'
elif is_pi ; then
echo 'Is Pi'
else
echo 'Not mac nor Pi'
fi
TS;DR
- macOS の場合は
sw_vers
コマンドが実行できるか否かで macOS か判断しています。 - RaspberryPi の場合は
/proc/cpuinfo
の CPU 情報から、モデル名に「ARMv
」が含まれているか否かで判断しています。 - RaspberryPi 同様、macOS も
system_profiler
で CPU で判断するのが確実ですが、コストを優先しました。CPU(アーキテクチャ)が ARM か AMD か Intel かを検知したい場合はsystem_profiler
を使う方がいいかもしれません。
sw_vers
コマンド
sw_vers
コマンドは、ローカルマシン上で走っている Mac OS X/Mac OS X Server のバージョン情報を表示します。
$ man sw_vers
の内容$ man sw_vers
SW_VERS(1) BSD General Commands Manual SW_VERS(1)
NAME
sw_vers -- print Mac OS X operating system version information
SYNOPSIS
sw_vers
sw_vers -productName
sw_vers -productVersion
sw_vers -buildVersion
DESCRIPTION
sw_vers prints version information about the Mac OS X or Mac OS X Server
operating system running on the local machine.
When executed with no options sw_vers prints a short list of version
properties:
% sw_vers
ProductName: Mac OS X
ProductVersion: 10.3
BuildVersion: 7A100
The ProductName property provides the name of the operating system
release (typically either "Mac OS X" or "Mac OS X Server"). The
ProductVersion property defines the version of the operating system
release (for example, "10.2.4" or "10.3"). The BuildVersion property
provides the specific revision of the operating system as generated by
the Mac OS X build system.
OPTIONS
The output of sw_vers can be refined by the following options.
-productName Print just the value of the ProductName property.
-productVersion Print just the value of the ProductVersion property.
-buildVersion Print just the value of the BuildVersion property.
EXAMPLES
% sw_vers -productName
Mac OS X
% sw_vers -productVersion
10.3
% sw_vers -buildVersion
7A100
FILES
/System/Library/CoreServices/SystemVersion.plist
/System/Library/CoreServices/ServerVersion.plist
Mac OS X March 10, 2003 Mac OS X
動作確認済み
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.13.6
BuildVersion: 17G65
$ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 8 (jessie)"
NAME="Raspbian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"
参考文献
- MacOSXのバージョンをコマンドラインで確認するには @ Qiita