简体   繁体   English

在bash中获得类似“ 310”的Linux内核版本?

[英]Get linux kernel version like this “310” in bash?

I create a script that I need the current kernel version in a specific way. 我以特定方式创建了需要当前内核版本的脚本。

For example, if I use : 3.10.34-1-MANJARO I want to get only 310 例如,如果我使用: 3.10.34-1-MANJARO我只想得到310

Which is the best/easy way to do it ? 最好/最简单的方法是什么?

You could use awk : 您可以使用awk

awk -F. '{print $1$2}' <<< "3.10.34-1-MANJARO"

or cut : cut

cut -d. -f1-2 --output-delimiter='' <<< "3.10.34-1-MANJARO"

To complement @devnull's helpful answer with a bash-only solution, using bash's regex-matching operator, =~ : 为了使用纯bash解决方案补充@devnull的有用答案,请使用bash的正则表达式匹配运算符=~

ver=$([[ $(uname -r) =~ ^([0-9]+)\.([0-9]+) ]];
      echo "${BASH_REMATCH[1]}${BASH_REMATCH[2]}")

echo "$ver" # e.g., -> '310', if `uname -r` returned "3.10.34-1-MANJARO"

An alternative solution using bash parameter expansion: 使用bash参数扩展的替代解决方案:

Note : This will only work if the output from uname -r contains a - in the 3rd . 注意 :如果从输出,此功能才能uname -r包含一个-在第三. -based component - this appears to the case for Linux distributions (but not, for instance, on OSX). 基于组件的组件-在Linux发行版中似乎是这种情况(例如,在OSX上则不是)。

ver=$(uname -r)          # get kernel release version, e.g., "3.10.34-1-MANJARO"
ver="${ver%.*-*}"        # remove suffix starting with '.' and containing '-'
ver="${ver//.}"          # remove periods (a single `/` would do here)

echo "$ver" # e.g., -> '310'

Tip of the hat to @alvits, who points out that uname -r may have an additional . @alvits的提示,后者指出uname -r可能还有一个额外的. component describing the architecture - eg 3.8.13-16.2.1.el6uek.x86_64 . 描述体系结构的组件-例如3.8.13-16.2.1.el6uek.x86_64

A 'Bash only' solution: “仅现金”解决方案:

declare -a TEMP2
TEMP1=$(uname --kernel-release)
TEMP2=(${TEMP1//[.-]/ })
VERSION=$(((${TEMP2[0]} * 100)\
    + ${TEMP2[1]}))
echo $VERSION

This will still work when the OP's version bumps up to something like 4.1 当OP的版本升至4.1之类时,这仍然可以使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM