Thanks to the course I’m doing, I now know that was done for compatibility with yum.
IIRC, isn’t yum just a symlink to dnf in /usr/bin?
Also, bash is bash, switching distro for it makes little sense. (assuming you are not using a distro with an out of date version of bash)
I guess the course you are taking is containing examples using bash to install stuff using dnf, and that is the reason?
Bash class in session:
Check for available package manager and install:
#!/usr/bin/env bash
if ! command -v firefox > /dev/null; then
echo "Firefox not installed"
while true; do
read -r -p 'Do you want to try to install Firefox? [y/n] ' input
case $input in
[Yy]) break;;
[Nn]) echo "Aborting..."; exit 1;;
*) echo "ERROR! Please enter 'y' or 'n'";;
esac
done
if command -v pacman > /dev/null; then
echo "pacman found on system, installing..."
sudo pacman -Syu firefox
elif command -v dnf > /dev/null; then
echo "dnf found on system, installing..."
dnf install firefox
elif command -v apt > /dev/null; then
echo "apt found on system, installing..."
sudo apt install firefox
else
echo "No supported package manager could be found\nInstalling Firefox failed!"
exit 1
fi
else
echo "Firefox already installed"
fi
exit 0
Or you can make it a bit cleaner by replacing the if statement by iterating over a collection of applications and then use a case statement to run found package manager:
for cmd in apt pacman dnf); do
command -v "$cmd" > /dev/null
if [[ "$?" -eq 0 ]]; then # $? is return/exit code for previous command, in this case 'command -v <application>'. 0=success 1=fail
echo "$cmd found, installing..."
break # break the for loop to make sure $cmd stays on the pkg_mgr found and 'false' is not being executed, ie exit code 0 (echo is actually the new $? but it will very likely succeed too)
else
false # false returns exit code 1 if no package manager is found
# this is a gatcha you can try. Uncomment the echo below and that will then return exit code 0 since it succeds, hence causing an error in the script due to wrong exit code beeing passed at the end of the for loop
#echo "by running this echo, exit code is now 0 even though no pgk_mgr was found. If you want an echo here, it has to be done BERFORE the 'false'"
fi
done
if [[ "$?" -ne 0 ]]; then # if no package manager is found false is ran as the last thing in the for loop, ie exit code 1
echo "No package manager found"
exit 1 # exits the script and nothing more is done, ie the case statement blow never runs
fi
case "$cmd" in
apt) sudo apt install firefox;;
pacman) sudo pacman -Syu firefox;;
dnf) dnf install firefox;;
esac
exit 0
Or even put the package managers you want to iterate over in an array:
pkg_mgr=(apt pacman dnf)
for cmd in "${pkg_mgr[@]}"; do
...
Class dismissed… xD
![]()