How can you tell the version of Ubuntu on a system in a .sh (bash) script?
Var=$(lsb_release -r)
echo "$Var"
Should do the trick.
For the numeric portion only add this:
NumOnly=$(cut -f2 <<< "$Var")
echo "$NumOnly"
The lsb-release
variables file
/usr/bin/lsb_release
is a Python script. It's a short script that serves as a good introduction to the python language. As others mentioned, a shorter way to get the version number only is with lsb_release -sr
.
The /etc/lsb-release
file defines environmental variables with the same information provided by the lsb_release -a
command:
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.6 LTS"
You can include these environment variables at anytime using . /etc/lsb-release
. To test in your terminal:
$ . /etc/lsb-release
$ echo $DISTRIB_RELEASE
16.04
$ echo $DISTRIB_DESCRIPTION
Ubuntu 16.04.6 LTS
An alternative is to use the /etc/os-release
file instead. This is formatted as a list of shell variables:
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.2 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.2 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
So an easy way of parsing it is to simply source
the file:
$ . /etc/os-release
$ echo $NAME
Ubuntu
$ echo $VERSION
18.04.2 LTS (Bionic Beaver)
$ echo $PRETTY_NAME
Ubuntu 18.04.2 LTS
$ echo $VERSION_ID
18.04
To avoid setting all these variables unnecessarily, you can source the file in a subshell, echo the variable you need and exit the subshell:
$ ( . /etc/os-release ; echo $VERSION_ID)
18.04
Alternatively, you can always just parse the file directly:
$ grep -oP 'VERSION_ID="\K[\d.]+' /etc/os-release
18.04
The lsb_release
command supports an -s
(or --short
) option to print just the information you ask for and not the header that says what kind of information that is.
To get just the version number it is thus sufficient to run:
lsb_release -sr
For example, on Ubuntu 18.04 LTS, that outputs:
18.04
As with the method in WinEunuuchs2Unix's answer, it is still reasonable to use command substitution to assign this output to a shell variable. Supposing you wanted the ver
variable to hold the release number:
ver="$(lsb_release -sr)"
With -s
, there's no need to parse out the number with cut
, sed
, grep
, awk
, more complex forms of parameter expansion, or the like.
In this usage, the "
"
quotes are optional, but I generally suggest quoting parameter expansion and other shell expansions except when there is a reason not to.