Sometimes you find out the need (and so do I) to have distro agnostic scripts, and when using package manager things can get distro bound very quickly.

So today I’m posting for you and me later, for whenever I need a script to find out the package manager or distro that is present at the target host im pointing some scripts at.


#!/bin/bash
declare -A osInfo;
osInfo[/etc/debian_version]="apt-get"
osInfo[/etc/alpine-release]="apk"
osInfo[/etc/centos-release]="yum"
osInfo[/etc/fedora-release]="dnf"

for f in ${!osInfo[@]}
do
    if [[ -f $f ]];then
        package_manager=${osInfo[$f]}
    fi
done

This is just an example for debian, alpine, centos and fedoras, but many more may be added.

How could one use it to install git, for instance indepently of the target host distro?

This is specially useful for tool installation on Jenkins slaves for instance.

Please do pay attention that this is a bash script, as declare is a bashism, won’t work without having bash installed, for instance in very vanilla alpine versions.

Example for git installation.

#!/bin/bash
declare -A osInfo;
osInfo[/etc/debian_version]="apt-get install -y"
osInfo[/etc/alpine-release]="apk --update add"
osInfo[/etc/centos-release]="yum install -y"
osInfo[/etc/fedora-release]="dnf install -y"

for f in ${!osInfo[@]}
do
    if [[ -f $f ]];then
        package_manager=${osInfo[$f]}
    fi
done

package="git"

${package_manager} ${package}

You can always improve this script to make it more robust and elastic.

Thanks for reading, hope you found it helpful.

André Ilhicas dos Santos

Devops Padawan, curious about systems automation, learning new languages, paradigms tools each day.

ilhicas ilhicas


Published