How to check if two or more programs are installed using a bash script?
I want to check whether two or more programs are installed using a bash script:
hash foo &> /dev/null
if [ $? -eq 1 ]; then
echo >&2 "foo not found."
else
echo "foo found"
fi
The above script works for a single program and I want to check for multiple programs installed in a system. How can I do that?
Solution 1:
If you want to check that all of them are installed, just do:
hash foo bar baz &>/dev/null &&
echo "All programs installed" ||
echo "At least one program is missing"
The &>
redirects standard error and standard output to /dev/null
so you don't print the output of hash
. You probably only need 2>
since as far as I know, hash
only prints to stderr, but we may as well be on the safe side.
The &&
means that the next command will only be run if the previous one was successful. The ||
means the next command will only be run if the previous one failed. So, if one of the three (or N) programs you checked for is not installed, you will get the error message.
If you want to be told which program is not installed, use this one instead:
for p in foo bar baz; do
hash "$p" &>/dev/null && echo "$p is installed" ||
echo "$p is not installed"
done
Finally, for even more fine grained control and detailed output, you could do:
i=0; n=0; progs=(foo bar baz);
for p in "${progs[@]}"; do
if hash "$p" &>/dev/null
then
echo "$p is installed"
let c++
else
echo "$p is not installed"
let n++
fi
done
printf "%d of %d programs were installed.\n" "$i" "${#progs[@]}"
printf "%d of %d programs were missing\n" "$n" "${#progs[@]}"