1

I am forming a new question based on an earlier one I posted here in regards to a BASH Script I am writing. This is only one function of the script but I started here because I figured I would have best success with completing this function over others.

The code that I have thus-far is:

#!/bin/bash
clear;
welcome="- Sudo Bypass Package Installer -";
echo $welcome;
pkgFetch() {
    echo -n "Name of package you would like to install: "; read pkg
    chkPkg=$(dpkg -s $pkg|grep installed); echo "The Package [$pkg] is already installed."
if [ "" == "$chkPkg" ]; then
    echo  "The Package [$pkg] is installing..."
    sudo apt-get install $pkg -qq
    echo  "The package [$pkg] was successfully installed."
fi
echo  -n "Press ENTER to return to command-line."
};
pkgFetch;
read;
clear;

The first part, which checks if the package is installed (if it is the script returns the message stating it's already installed) appears to be working correctly. However, I encounter a few things here that I can't make sense of...mostly because I am a novice.

  • If [$pkg] is not installed, the script still displays the message saying that it is, followed by the message that should be displayed if not installed, which is that it is currently installing.
  • The script doesn't silently install the package. It shows that it is reading database, unpacking $pkg, processing triggers, and setting up $pkg. Afterwards, the script displays the correct message that "The package [$pkg] was successfully installed".

Anyone want to take a shot at it here and educate me about my errors?

Thanks in advance : - )

1 Answers1

2

the message saying, that the package is already installed is completely unconditional, it is displayed wether the grep returns successful or not.

You could prepend it with [ -n "$chkPkg" ] && to make it conditional (on a nonempty chkPkg variable), or even better pull it into the if block like that:

if [ "" == "$chkPkg" ]; then
  echo  "The Package [$pkg] is installing..."
  # ...
else
  echo "The Package [$pkg] is already installed."
fi

BTW. You should match variables in shellscript with a single =, not with ==. The latter is not posix conform and will not run in some unix shells apart from bash. Such things are called "bashisms", avoid them where it doesn't inconvenience you too much.

Paul Hänsch
  • 3,237