I'm trying to write a script that installs packages, like `python3`, and it should work on both Ubuntu and Fedora. I know that Ubuntu uses `apt` while Fedora uses `dnf`, so I started with a simple conditional statement:
if [ $(apt --version) ] ; then
sudo apt install python3
else
sudo dnf install python3
However, I'm having trouble figuring out how to correctly check for the `apt` version to return a true value and switch to using `dnf` if it's not present. Any suggestions on how to get this working?
5 Answers
For a bash script, another way is to identify the package manager with:
```bash
if command -v dnf &> /dev/null; then
PACKAGE_MANAGER="dnf"
elif command -v apt-get &> /dev/null; then
PACKAGE_MANAGER="apt"
else
echo "Error: No supported package manager found."
fi
sudo $PACKAGE_MANAGER install -y your-package-here
```
This simplifies package installation without worrying too much about distro specifics.
I wouldn't recommend trying to install using different package names across distros. You could run into dependency issues. It’s better to directly work with the specific package names on each distro instead.
Instead of checking just for `apt`, you'll want to branch based on the distribution. The best way is to use the `ID` variable from the `/etc/os-release` file which tells you the specific distribution. Here's a quick template:
```
source /etc/os-release
case "$ID" in
debian|ubuntu)
sudo apt-get update
sudo apt-get install -y curl git jq build-essential
;;
fedora)
sudo dnf install -y curl git jq @development-tools
;;
# add more cases as needed...
esac
```
This way, you can handle different package managers based on the actual distro.
This is the correct approach, and while tools like Ansible help with this, it's good to have the basics down.
This might be exactly what I'm looking for. Thank you!
Just a heads up, if you're trying to install the same RPM packages on both Fedora and Ubuntu, you might want to check out the `alien` package. It's not foolproof, but it can help install RPMs on Debian-based systems.
Consider using Ansible for this task. It has built-in logic for handling different package managers, which makes it easier to set up installations depending on the system type.
Exactly! If you plan to do more of this in the future, Ansible makes life simpler.
There's definitely a purpose-built solution for managing this in Ansible, it can save a lot of hassle.
I have a script where I set flags for each distro so I can easily use logic like: if $fedora; then elif $arch; then...