I am writing a script to install packages from .deb files, but first, I would like to check if each package is already installed. I have a config file that contains the information for the packages as hashmaps, like this:
declare -A package_a=(
[name]="utility-blah"
[ver]="1.2"
[arch]="amd64"
)
declare -A package_b=(
[name]="tool-bleh"
[ver]="3.4"
[arch]="all"
)
#and so on and so forth
My install script sources the config file, and I would like it to iterate over the packages, checking if they are installed, and installing them if they are not, like this:
source packages.config
declare -a packageList=("package_a" "package_b" "package_d")
for package in ${packageList[@]}; do
# Check if the specific version is installed already
if apt show ${package[name]}=${package[ver]}; then
echo ${package[name]} ${package[ver]} is already installed.
else
echo Installing ${package[name]}
sudo apt install path/to/files/${package[name]}_${package[ver]}_${package[arch]}.deb
fi
done
How can I have package
point to the hashmap containing the information about the package and use it in the following commands?
I’m using Bash 4.4.20 on Ubuntu 18.04
2
Answers
One idea using a nameref:
Or (as M. Nejat Aydin and Benjamin W. have pointed out) the
declare -n
can go before thewhile
loop, eg:Simple test:
This generates:
This kind of input data is better suited for JSON rather than using bash associative arrays and indirection.
Lets say you have a
packages.json
:Such simple POSIX-shell script is able to process it as you need:
Example output: