bash 检查操作系统版本,如果版本正确则发出命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9913942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:53:35  来源:igfitidea点击:

Check version of OS then issue a command if the correct version

macosbashoperating-systemosx-lionsh

提问by Bryan Larson

i am writing a bash script for Mac OS X Lion 10.7 and i would like to know how i can check the version of the OS in bash and if the version is lets say 10.7.1 then it does a command and continues with the script and do the same thing for a different version lets say 10.7.3 then it does a different command then the command that used for 10.7.1?

我正在为 Mac OS X Lion 10.7 编写 bash 脚本,我想知道如何在 bash 中检查操作系统的版本,如果版本是 10.7.1,那么它会执行一个命令并继续执行脚本和对不同的版本做同样的事情让我们说 10.7.3 然后它执行不同的命令然后是用于 10.7.1 的命令?

回答by E1Suave

OS_Version (full… example 10.7.3)

OS_Version(完整……示例 10.7.3)

system_profiler SPSoftwareDataType | grep "System Version" | awk '{print }'

OR

或者

sw_vers -productVersion

OS (short… example 10.7)

操作系统(简短……示例 10.7)

system_profiler SPSoftwareDataType | grep "System Version" | awk '{print }' | sed "s:.[[:digit:]]*.$::g"

OR

或者

OS_Version=$(OS (short… example 10.7) | sed "s:.[[:digit:]]*)

bash:

重击:

#!/bin/bash

# Use one of the examples given above to create the OS_Version variable

if [[ ${OS_Version} == 10.7.3 ]]; then
   echo "Operating System is a match... will continue on."
else
   echo "Operating System is NOT a match... will NOT continue."
fi

回答by zmccord

You want the sw_verscommand on OS X. It prints some human-readable strings, including the 10.X.X system version (sw_vers -productVersion). You can also use unameto check the kernel version; if your script is ever ported to other Unix variants unamewill work there.

您需要sw_versOS X 上的命令。它会打印一些人类可读的字符串,包括 10.XX 系统版本 ( sw_vers -productVersion)。也可以uname用来查看内核版本;如果您的脚本曾经被移植到其他 Unix 变体uname将在那里工作。

回答by user4271824

If you only need to check the major OS version, keep in mind the Darwin version corresponds to it, and within bash is set to a shell variable that is easy to coerce to a numerically comparable integer.

如果您只需要检查主要操作系统版本,请记住 Darwin 版本与其对应,并且在 bash 中设置为一个 shell 变量,该变量易于强制转换为数字可比较的整数。

if [[ ${OSTYPE:6} -ge 13 ]]; then
    echo "At least 10.9, so feeling fine.";
else 
    echo "Time to put the old cat to sleep.";
fi