Today, I want to briefly describe a simple way to check for a specific package inside a shell script.
The following function uses dpkg-query
utility to examine if a specified package is installed. In case of failure, it examines if the package is available in locally configured repositories using apt-cache
command.
# check for specific package # Return values: # 0 - package is installed # 1 - package is not installed, it is available in package repository # 2 - package is not installed, it is not available in package repository check_for_package(){ if dpkg-query -s "$1" 1>/dev/null 2>&1; then return 0 # package is installed else if apt-cache show "$1" 1>/dev/null 2>&1; then return 1 # package is not installed, it is available in package repository else return 2 # package is not installed, it is not available in package repository fi fi }
Regular shell script to illustrate the usage.
#!/bin/sh # check for specific package # Return values: # 0 - package is installed # 1 - package is not installed, it is available in package repository # 2 - package is not installed, it is not available in package repository check_for_package(){ if dpkg-query -s "${1}" 1>/dev/null 2>&1; then return 0 # package is installed else if apt-cache show "$1" 1>/dev/null 2>&1; then return 1 # package is not installed, it is available in package repository else return 2 # package is not installed, it is not available in package repository fi fi } # example packages="bash bashdb mc openssl-dev type" for package in $packages; do if check_for_package "$package"; then printf "%-20s - %s\n" "$package" "package is installed" else if test "$?" -eq 1; then printf "%-20s - %s\n" "$package" "package is not installed, it is available in package repository" else printf "%-20s - %s\n" "$package" "package is not installed, it is not available in package repository" fi fi done
Sample output.
bash - package is installed bashdb - package is not installed, it is available in package repository mc - package is installed openssl-dev - package is not installed, it is not available in package repository type - package is not installed, it is not available in package repository
Additional notes
I cannot use simple &>/dev/null
redirection as dash
command interpreter does not support it, so I need to take advantage of the longer 1>/dev/null 2>&1
version to get rid of the whole (standard and error) output inside shell functions.