Return true if printers installed

dletkeman
Contributor II

We are trying to push out a script that deletes all printers. That part of it works just fine.

We use the following:

# Get all printers and remove them
# Log printer names
echo "Removing all printers..."
for printer in `lpstat -p | awk '{print $2}'`
do
  echo $printer >> "/Library/LOGGINGFOLDER/$logname"
  lpadmin -x $printer
done

We use logging in case we need to reinstall anything later.

Problem is that when there aren't any printers to delete then the exit code is 1 and an error notification is triggered. How do I test if printers are installed before continuing? else would be exit with code 0 (success).

Thanks for the help!

2 REPLIES 2

mm2270
Legendary Contributor III

Simplest thing is to store the results of lpstat -p | awk '{print $2}' into a variable first in the script. Then have an if/then block that tests to see if the variable is populated with data or not. It would be empty if no printers are installed. If it's not a null value, then proceed with the removals.

#!/bin/bash

Installed_Printers=$(/usr/bin/lpstat -p | awk '{print $2}')

if [ -n "$Installed_Printers" ]; then
    for printer in $Installed_Printers; do
        echo $printer >> "/Users/mikem/Desktop/logfile1.log"
        /usr/sbin/lpadmin -x $printer
    done
else
    echo "No printers installed"
fi

dletkeman
Contributor II

Thanks! That did the trick!