I'm trying to write a script that detects the Linux OS and version and through the use of conditions and operators execute different commands depending on the result.
Detect OS
if [ -f /etc/os-release ]; then
. /etc/os-release
OS="$NAME"
OS_version="$VERSION_ID"
elif [ -f /etc/debian_version ]; then
# Older Debian/Ubuntu/etc.
OS="Debian"
OS_version="$(cat /etc/debian_version)"
fi
If I echo these variables they return with
$ echo $OS
Debian GNU/Linux
$ echo $OS_version
10
In my example below I want to match Debian and OS version 10. However, the $OS variable contains more that just the word Debian so I need some kind of wildcard so I can do a partial match.
The only way I've found to get this to work in through command substitution by echoing the $OS variable to stdout and piping it into the grep command which then does a wildcard search. This is the if statement I came up with in the end:
if [ "$(echo "$OS" | grep 'Debian*')" -a "$OS_version" -ge 10 ]; then
echo "OS is Debian"
sleep 4
else
echo "OS is other"
sleep 4
fi
As I will be using this script on other Unix based OSs so I would like to make this script as widely compatible as possible and stick to POSIX standards.
While testing my script on Ubuntu 21.04 I discovered that Linux has trouble working out which number is greater than another when there is decimal place involved. Below I've created two shell scripts which export a two-integer number with a two-decimal place and uses an if statement to check if it's greater and/or equal to another number.
20.10.sh
#!/bin/sh
export OS_version="20.10"
if [ "$OS_version" -ge 21.04 ]; then
echo "Your OS is new enough"
sleep 2
else
echo "Your OS is too old!"
sleep 2
fi
20.10.sh output
~$ ./20.10.sh
YOUR OS VERSION IS >> 20.10
./20.10.sh: 6: [: Illegal number: 20.10
Your OS is too old!
23.45.sh
#!/bin/sh
export OS_version="23.45"
if [ "$OS_version" -ge 21.04 ]; then
echo "Your OS is new enough"
sleep 2
else
echo "Your OS is too old!"
sleep 2
fi
23.45.sh output
~$ ./23.45.sh
YOUR OS VERSION IS >> 23.45
./23.45.sh: 6: [: Illegal number: 23.45
Your OS is too old!
The 23.45.sh script should echo "Your OS is new enough" but doesn't and displays an error of an illegal number.
Is there a way to detect the size of different numbers with decimal places in?