Recursive printer removal

cddwyer
Contributor

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?

1 ACCEPTED SOLUTION

davidacland
Honored Contributor II
Honored Contributor II

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

View solution in original post

3 REPLIES 3

davidacland
Honored Contributor II
Honored Contributor II

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
Valued Contributor

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.

cddwyer
Contributor

@davidacland Thanks very much that worked a treat!

Have a great day.