This script checks for if the Mac is an M1 Chip, then if it is not, will check for the OS. Depending on these conditions, the year will be read differently.
#!/bin/sh #Set variables for processor, apple chip, & operating system version
processor=$(/usr/sbin/sysctl -n machdep.cpu.brand_string )
AppleChip="Apple M1"
AppleChipYear=$(/usr/libexec/PlistBuddy -c "print :'CPU Names'" ~/Library/Preferences/com.apple.SystemProfiler.plist | tr ' ' ' ' | grep -e "M1, 20[0-9][0-9]" -e "20[0-9][0-9]" | sed 's/[[:punct:]]$//' )
os_ver=$(sw_vers -productVersion | awk -F. '{print $2}')
os_ver2=$(sw_vers -productVersion | awk -F. '{print $1}')
#check if the machine is an Apple M1 processor
if [[ "$processor" == *"$AppleChip"* ]]; then
echo "$AppleChipYear" else
#Check which operating system version is on the mac if not an Apple M1 chip processor
if [[ ${os_ver} -le 14 ]] && [[ ${os_ver2} -le 10 ]]; then plistFile="/System/Library/PrivateFrameworks/ServerInformation.framework/Versions/A/Resources/English.lproj/SIMachineAttributes.plist"
sysModel=$(sysctl hw.model | awk '{print $NF}')
modelYear=$(/usr/libexec/PlistBuddy -c "Print ${sysModel}:_LOCALIZABLE_:marketingModel" "$plistFile" | tr ' ' '\\n' | grep -o "20[0-9][0-9]") if [ ! -z "$modelYear" ]; then
echo "$modelYear"
else
echo "N/A"
fi
elif [[ ${os_ver} -ge 15 ]]; then plistFile="/System/Library/PrivateFrameworks/ServerInformation.framework/Versions/A/Resources/en.lproj/SIMachineAttributes.plist"
sysModel=$(sysctl hw.model | awk '{print $NF}') modelYear=$(/usr/libexec/PlistBuddy -c "Print ${sysModel}:_LOCALIZABLE_:marketingModel" "$plistFile" | tr ' ' '\\n' | grep -o "20[0-9][0-9]") if [ ! -z "$modelYear" ]; then
echo "$modelYear"
else
echo "N/A"
fi
elif [[ ${os_ver} -le 14 ]] && [[ ${os_ver2} -ge 11 ]]; then
plistFile="/System/Library/PrivateFrameworks/ServerInformation.framework/Versions/A/Resources/en.lproj/SIMachineAttributes.plist"
sysModel=$(sysctl hw.model | awk '{print $NF}')
modelYear=$(/usr/libexec/PlistBuddy -c "Print ${sysModel}:_LOCALIZABLE_:marketingModel" "$plistFile" | tr ' ' ' ' | grep -e "M1, 20[0-9][0-9]" -e "20[0-9][0-9]" | sed 's/[[:punct:]]$//')
if [ ! -z "$modelYear" ]; then
echo "$modelYear"
else
echo "N/A"
fi
fi
fi
#end
exit 0