As we all know, the command we use in order to install multiple packages is:
apt install package1 package2 package3`
Using the following method in a Bash script:
packages="package1 package2 package3"
apt install "$packages"
produces an error saying that the package cannot be located. Therefore it's incorrect.
Does the following command run apt
once for each package or does it work differently?
apt install $(cat $packageFile)
assuming that packageFile is a text file containing the package names one per line.
I know that I can use an array and place all package names in it and then use a for loop to run apt
once for each package, but I'm wondering if there's a way to install all of them, using a Bash script, running apt
only once.
Thank you.
The approach of using an array is correct, but you need to define properly the array. This means that you need to use a compound statement (i.e. round brackets) instead of double quotes. In fact, the reason why your command does not work in the first place is because
$packages
gets expanded by the shell topackage1 package2 package3
which is then read as a single string byapt
, not separately aspackage1
,package2
,package3
.Therefore, define an array using a compound assignment in the following form:
and then install all the packages using the following command:
In fact, any element of an array may be referenced using
${array_name[index]}
, and when the index is@
, the word expands to all members of the array name. The use of braces is required to avoid conflicts with the shell’s filename expansion operators.