Date:

Share:

Linux distro conditionals in shell script by Josh Sherman

Related Articles

It’s happening again. I got a little tired of Debian, and began to crave all the bloody edge glory that is Arch. Since this is a semi-frequent occurrence in my life, I’ve been able to juggle distributions within my shell scripts quite well, especially in dotfiles.

Since each system has its own little way of doing certain things, I had to implement conditions that check which system I’m on. The Node.js version manager nvm is a great example of this, because shell scripts you need to source from your shell profile are installed in wildly different places.

Debian, Arch, as well as macOS should be considered, as I bounce between these systems regularly.

Unfortunately, you can’t just rely on uname For anything other than macOS, as it just returns Linux No matter what Linux distribution you are on. the solution? Check if the distribution’s package manager du jour is available.

If it’s available, there’s a good chance you’re on that distribution. While I don’t have a 100% guarantee, I haven’t had any issues with this method yet, so it’s as close to perfect as I need it to be.

This is what conditional handling looks like on macOS, Debian and Arch:

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

Obviously an ID apt Might as well say it’s an Ubuntu system, but that really only matters if a) I was running Ubuntu, and b) if Ubuntu had some deviation from Debian.

You can extend it as you see fit as well, including checks for Red Hat, Gentoo, Alpine, and the like.

good things? want more?

Weekly emails about technology, development and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Source

Popular Articles