Skip to main content
Solved

Recursive printer removal

  • August 30, 2016
  • 3 replies
  • 17 views

Forum|alt.badge.img+7

Hi I want to recursively remove all printers of a certain model number with a script, what I have so far is the below but while testing the script seems to exit with 0.

#!/bin/bash

function rmPrinters {
    thisPrinter=""
    thisPrinter=`lpstat -p | grep X7855 | head -1 | cut -d " " -f 2`
    if [ -z "$thisPrinter" ]; then
        exit 0
    else
        lpadmin -x $thisPrinter
        rmPrinters{}
    fi
}

Can anyone help figure out why this is not working?

Best answer by davidacland

I haven't used -z before, is that to check if the variable is populated? The rest all looks ok so I'd assume it's that telling the script to exit 0.

Another way to see if the variable is empty would be:

if [ "$thisPrinter" = "" ]; then...

That aside, I'd probably go about it a different way using a loop:

#!/bin/bash 

counter=$(lpstat -p | grep -c X7855)
    # Outputs the number of found printers matching X7855

while [ $counter -ne 0 ]

    do
        thisPrinter=$(lpstat -p | grep X7855 | head -1 | cut -d " " -f 2)
        lpadmin -x $thisPrinter
        counter=$(( $counter - 1 ))
            # Reduces the counter by 1
done

exit 0

3 replies

davidacland
Forum|alt.badge.img+18
  • Valued Contributor
  • Answer
  • August 30, 2016

I haven't used -z before, is that to check if the variable is populated? The rest all looks ok so I'd assume it's that telling the script to exit 0.

Another way to see if the variable is empty would be:

if [ "$thisPrinter" = "" ]; then...

That aside, I'd probably go about it a different way using a loop:

#!/bin/bash 

counter=$(lpstat -p | grep -c X7855)
    # Outputs the number of found printers matching X7855

while [ $counter -ne 0 ]

    do
        thisPrinter=$(lpstat -p | grep X7855 | head -1 | cut -d " " -f 2)
        lpadmin -x $thisPrinter
        counter=$(( $counter - 1 ))
            # Reduces the counter by 1
done

exit 0

iJake
Forum|alt.badge.img+23
  • Contributor
  • August 30, 2016

First you can replace

| head -1 | cut -d " " -f 2

with just an

awk '{print $2}'

Second, I think a for loop would work better and then there is no need for a counter.


Forum|alt.badge.img+7
  • Author
  • Contributor
  • August 31, 2016

@davidacland Thanks very much that worked a treat!

Have a great day.