I took some ideas from here and a one liner from elsewhere to get the distro and you have this. I'm using this as part of container image builds. Let's me do "generic" installs without having to know apriori the distro of the base image. Of course if a package name varies from distro to distro this one fits all fails as is.
#!/bin/bash
pkg_install () {
local distro;local cmd;local usesudo
declare -A pkgmgr
pkgmgr=(
[arch]="pacman -S --noconfirm"
[alpine]="apk add --no-cache"
[debian]="apt-get install -y"
[ubuntu]="apt-get install -y"
)
distro=$(cat /etc/os-release | tr [:upper:] [:lower:] | grep -Poi '(debian|ubuntu|red hat|centos|arch|alpine)' | uniq)
cmd="${pkgmgr[$distro]}"
[[ ! $cmd ]] && return 1
if [[ $1 ]]; then
[[ ! $EUID -eq 0 ]] && usesudo=sudo
echo installing packages command: $usesudo $cmd $@
$usesudo $cmd $@
else
echo $cmd
fi
}
if script was executed then call the function
(return 0 2>/dev/null) || pkg_install "$@"
you can run it directly or source it and call the function. I don't use centos or redhat but you can add their entries to the array, or remove ones you don't want to support.
I had to write a posix version (because some base images like alpine don't have bash installed by default) so here is that
#!/bin/sh
hm_hash() {
echo "$1" | md5sum -
}
hm_put() {
echo "$3" > "$1/$(hm_hash "$2")"
}
hm_get() {
cat "$1/$(hm_hash "$2")"
}
pkg_install () {
local distro;local cmd;local usesudo; local pkgmgr
pkgmgr="$(mktemp -d)"
hm_put "$pkgmgr" arch "pacman -S --noconfirm"
hm_put "$pkgmgr" alpine "apk add --no-cache"
hm_put "$pkgmgr" debian "apt-get install -y"
hm_put "$pkgmgr" ubuntu "apt-get install -y"
distro=$(cat /etc/os-release | tr [:upper:] [:lower:] | grep -Poi '(debian|ubuntu|red hat|centos|arch|alpine)' | uniq)
cmd=$(hm_get "$pkgmgr" $distro 2> /dev/null)
rm -rf $pkgmgr
if [ ! -z "$cmd" ]; then
if [ -z "$1" ]; then
echo $cmd
else
echo installing packages command: $cmd $@
$cmd $@
fi
else
return 1
fi
}
if script was executed then call the function
(return 0 2>/dev/null) || pkg_install "$@"