今天写了一个shell函数来查编译环境的python版本,感觉还是学到了不少新东西,简单记录一下,能写出一点东西满足自己的需求也是一件开心的事情。
1. awk果然强大,本来也没有用过,上网了解了一些基本用法,解决了我的需求
2. SHELL里比较浮点数的大小确实很麻烦,还好这次小数点后只有两位
#!/bin/sh checkPython() { #推荐版本V3.8.0 V1=3 V2=8 V3=0 echo need python version is : $V1.$V2.$V3 #获取本机python版本号。如果是python2的环境这里2>&1是必须的,因为python2的-V参数命令是标准错误输出的,需要转换。python3就不是了。 U_V1=`python -V 2>&1|awk '{print $2}'|awk -F '.' '{print $1}'` U_V2=`python -V 2>&1|awk '{print $2}'|awk -F '.' '{print $2}'` U_V3=`python -V 2>&1|awk '{print $2}'|awk -F '.' '{print $3}'` echo your python version is : $U_V1.$U_V2.$U_V3 if [ $U_V1 -lt $V1 ];then echo 'Your python version is not OK!(1)' return 1 elif [ $U_V1 -eq $V1 ];then if [ $U_V2 -lt $V2 ];then echo 'Your python version is not OK!(2)' return 2 elif [ $U_V2 -eq $V2 ];then if [ $U_V3 -lt $V3 ];then echo 'Your python version is not OK!(3)' return 3 fi fi fi echo Your python version is OK! return 0 } checkPython recode=$? if [ $recode -eq 0 ];then echo "checkPython OK." else echo "checkPython failed. recode=" $recode fi
执行结果如下
./1.sh need python version is : 3.8.0 your python version is : 3.9.6 Your python version is OK! checkPython OK.