Home Bash script to find package manager in multiple linux distros
Post
Cancel

Bash script to find package manager in multiple linux distros

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/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.

This post is licensed under CC BY 4.0 by the author.