installpkg 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env bash
  2. # Identify host OS and execute package manager install command on input args
  3. #
  4. installpkg() {
  5. getOS() {
  6. # Widely supported method to retrieve host $ID
  7. if [[ -e /etc/os-release ]]; then
  8. source /etc/os-release
  9. else
  10. echo "No /etc/os-release found!"
  11. echo "Your OS is unsupported!"
  12. return 1
  13. fi
  14. }
  15. setCmdArr () {
  16. declare -ga CMD_ARR
  17. # Create OS-specific package install command arrays
  18. if [[ "$ID" == "fedora" ]]; then
  19. CMD_ARR=( "dnf" "install" "-y" )
  20. elif [[ "$ID" == "centos" && "$VERSION_ID" -ge 8 ]]; then
  21. CMD_ARR=( "dnf" "install" "-y" )
  22. elif [[ "$ID" == "centos" && "$VERSION_ID" -le 7 ]]; then
  23. CMD_ARR=( "yum" "install" "-y" )
  24. elif [[ "$ID" == "ubuntu" || "$ID" == "debian" ]]; then
  25. CMD_ARR=( "apt-get" "install" "-y" )
  26. elif [[ "$ID" == "arch" ]]; then
  27. CMD_ARR=( "pacman" "-Syu" )
  28. else
  29. echo "Your OS is currently unsupported! You are welcome to add your own and submit a PR."
  30. return 1
  31. fi
  32. # Append sudo if not running as root
  33. [[ "$(whoami)" != "root" ]] && CMD_ARR=( "sudo" "${CMD_ARR[@]}" )
  34. }
  35. installPackage() {
  36. # Check for input arguments
  37. if [[ "$#" -ge 1 ]]; then
  38. if ! "${CMD_ARR[@]}" "$@"; then
  39. echo "Installation failed!"
  40. return 1
  41. fi
  42. else
  43. echo "You must supply one or more packages to install!"
  44. return 1
  45. fi
  46. }
  47. main() {
  48. getOS && \
  49. setCmdArr && \
  50. installPackage "$@" && \
  51. unset CMD_ARR
  52. }
  53. main "$@"
  54. }
  55. if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  56. installpkg "$@"
  57. exit $?
  58. fi