Linux distro conditionals in shell script

It’s happening again. I’ve grown a bit tired of Debian, and have started to long for all the bleeding edge glory that is Arch. As this is a semi-frequent occurrence in my life, I’ve gotten pretty good at juggling distributions within my shell scripts, specifically in my dotfiles.

Since each system has it’s own little nuance way to do certain things, I’ve had to implement conditionals that check which system I’m on. The Node.js Version Manager nvm is a great example of this, as it’s shell scripts that you need to source from your shell profile get installed to wildly different places.

Debian, Arch, as well as macOS all have to be accounted for, as I jump between those systems on the regular.

Sadly, you can’t simply rely on uname for anything other than macOS, as it simply returns Linux regardless which Linux distribution you’re on. The solution? Check to see if the distro’s package manager du jour is available.

If it’s available, there is a good chance you’re on that distro. While not a 100% guarantee, I’ve yet to run into any problems with this method, so it’s as close to perfect as I need it to be.

Here’s what a conditional handling macOS, Debian and Arch looks like:

if [[ `uname` == Darwin ]]; then
  # Do the macOS stuff...
elif command -v apt &> /dev/null; then
  # Do the Debian stuff...
elif command -v pacman &> /dev/null; then
  # Do the Arch stuff...
else
  # You could error when encountering an "unknown" system, perhaps...
fi
PHP

Obviously detecting apt could also mean it’s an Ubuntu system, but this really
only matters if a) I ran Ubuntu, and b) if Ubuntu had some deviation from Debian.

You could expand this as you see fit as well, including checks for Red Hat,
Gentoo, Alpine, and the like.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.