Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  18] [ 0]  / answers: 1 / hits: 25652  / 3 Years ago, tue, july 6, 2021, 1:20:21

I have a simple requirement. I want to define several variables that will correspond to any number of given packages I want to install via a shell script.



Sample code below:



MISC="shutter pidgin"
WEB="apache2 mongodb"

for pkg in $MISC $WEB; do
if [ "dpkg-query -W $pkg | awk {'print $1'} = """ ]; then
echo -e "$pkg is already installed"
else
apt-get -qq install $pkg
echo "Successfully installed $pkg"
fi
done


Everything kinda works, but the logic seems flawed because it's not reliably installing the packages I want. It either says they've been installed already or it's trying to install packages that have already been installed previously.



I've also been trying with command -v or the following:



if [ "dpkg -l | awk {'print $2'} | grep --regexp=^$pkg$ != """ ]; then


And even with the -n and -z flags to check if the returned string was empty. Pretty sure I'm missing some good sense here.



Do you have any idea what I could do to make sure a package is actually installed or not?



Thanks!


More From » scripts

 Answers
0

Essentially you only need to replace the if condition with



if dpkg --get-selections | grep -q "^$pkg[[:space:]]*install$" >/dev/null; then


It is not possible to use dpkg-query, because it returns true also for packages removed but not purged.



Also I suggest to check the exit code of apt-get before giving the successful message:



if apt-get -qq install $pkg; then
echo "Successfully installed $pkg"
else
echo "Error installing $pkg"
fi

[#30346] Wednesday, July 7, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
thellfi

Total Points: 222
Total Questions: 103
Total Answers: 123

Location: Palau
Member since Mon, Aug 16, 2021
3 Years ago
thellfi questions
;