Dr.Avalanche
Dr.Avalanche

Reputation: 1996

Bash script - determine vendor and install system (apt-get, yum etc)

I'm writing a shell script for use on various linux platforms. Part of the script installs a couple of packages. How can I determine the linux vendor and default system install mechanism, for example Debian/Ubuntu has apt-get/apt, Fedora has yum and so on...

Thanks in advance

Upvotes: 10

Views: 8425

Answers (2)

Moazzem Hossen
Moazzem Hossen

Reputation: 2516

#!/bin/bash
set -ex

OS=$(uname -s | tr A-Z a-z)

case $OS in
  linux)
    source /etc/os-release
    case $ID in
      debian|ubuntu|mint)
        apt update
        ;;

      fedora|rhel|centos)
        yum update
        ;;

      *)
        echo -n "unsupported linux distro"
        ;;
    esac
  ;;

  darwin)
    brew update
  ;;

  *)
    echo -n "unsupported OS"
    ;;
esac

Upvotes: 1

Sebastien
Sebastien

Reputation: 1476

You don't really need to check for vendor as they may decide to change packaging system (unlikely but conceptually, you would have to ensure that for each distro you test for, you try the right package manager command). All you have to do is test for the installation itself:

  YUM_CMD=$(which yum)
  APT_GET_CMD=$(which apt-get)
  OTHER_CMD=$(which <other installer>)

and then possibly sort them in your preference order:

 if [[ ! -z $YUM_CMD ]]; then
    yum install $YUM_PACKAGE_NAME
 elif [[ ! -z $APT_GET_CMD ]]; then
    apt-get $DEB_PACKAGE_NAME
 elif [[ ! -z $OTHER_CMD ]]; then
    $OTHER_CMD <proper arguments>
 else
    echo "error can't install package $PACKAGE"
    exit 1;
 fi

you can take a look at how gentoo (or framework similar to yocto or openembedded) provide approach to even get the source code (with wget) and build from scratch if you want a failsafe script.

Upvotes: 20

Related Questions