4

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?

  • So why don't you just copy these lines? – davidbaumann Jun 13 '15 at 16:13
  • Do you just want to confirm whether both are found, or do you want to display the individual status of each? – steeldriver Jun 13 '15 at 16:13
  • @steeldriver I want to confirm whether both are installed or not and don’t want the individual status of the programmes – potholiday Jun 13 '15 at 16:28
  • @davidbaumann I don’t want the individual status of two programs. I just want to check if two of the programs are installed or not – potholiday Jun 13 '15 at 16:30
  • some thing like this hash foo &> /dev/null || hash goo &> /dev/null but if foo is installed and goo is not installed it still shows programs exists – potholiday Jun 13 '15 at 16:33
6

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[@]}"
  • 1
    Another day saved by terdon :). Thanks for the script – potholiday Jun 13 '15 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.