Linux – How to Find Out What Version is Running

linuxscripting

Sometimes your scripts need to behave differently on different Linux's. How can I determine which version of Linux a script is running on?

Best Answer

Don't try and make assumptions based on the distro as to what you can and cannot do, for that way lies madness (see also "User Agent detection"). Instead, detect whether what it is that you want to do is supported, and how it's done by whatever command or file location you want to use.

For example, if you wanted to install a package, you can detect whether you're on a Debian-like system or a RedHat-like system by checking for the existence of dpkg or rpm (check for dpkg first, because Debian machines can have the rpm command on them...). Make your decision as to what to do based on that, not just on whether it's a Debian or RedHat system. That way you'll automatically support any derivative distros that you didn't explicitly program in. Oh, and if your package requires specific dependencies, then test for those too and let the user know what they're missing.

Another example is fiddling with network interfaces. Work out what to do based on whether there's an /etc/network/interfaces file or an /etc/sysconfig/network-scripts directory, and go from there.

Yes, it's more work, but unless you want to remake all the mistakes that web developers have made over the past decade or more, you'll do it the smart way right from the start.