Check if an apt-get package is installed and then install it if it's not on Linux

后端 未结 22 1313
轮回少年
轮回少年 2020-12-02 04:02

I\'m working on a Ubuntu system and currently this is what I\'m doing:

if ! which command > /dev/null; then
   echo -e \"Command not found! Install? (y/n)         


        
22条回答
  •  借酒劲吻你
    2020-12-02 04:23

    To be a little more explicit, here's a bit of bash script that checks for a package and installs it if required. Of course, you can do other things upon finding that the package is missing, such as simply exiting with an error code.

    REQUIRED_PKG="some-package"
    PKG_OK=$(dpkg-query -W --showformat='${Status}\n' $REQUIRED_PKG|grep "install ok installed")
    echo Checking for $REQUIRED_PKG: $PKG_OK
    if [ "" = "$PKG_OK" ]; then
      echo "No $REQUIRED_PKG. Setting up $REQUIRED_PKG."
      sudo apt-get --yes install $REQUIRED_PKG 
    fi
    

    If the script runs within a GUI (e.g. it is a Nautilus script), you'll probably want to replace the 'sudo' invocation with a 'gksudo' one.

提交回复
热议问题