Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

gpchess2k

macrumors member
Original poster
Oct 12, 2015
42
0
Hello, I am looking for help on adding loop statements to my current working bash script. What the script does is look for a particular printer by protocol and remove it. What I would love to do is remove ALL printers found with that protocol. I have played with a few examples of 'while' and 'until' loop statements but can't seem to get it right. Code is a bit messy and I'm sure it can be simplified.


Code:
printer1=$(lpstat -s | grep '10.18.28.17' | awk -F'/' '{print $3}')
printer01=$(lpstat -s | grep 'smb://sea22233.internal.company.com/SEC2-Canon' | awk -F'/' '{print $3}')

if [ -z $printer1 ]; then
:
else
remove_printer1=$(lpstat -s | grep '10.18.28.17' | awk -F ' ' '{print $3}' | sed s/://g)
lpadmin -x $remove_printer1
remove_printer2=$(lpstat -s | grep 'lpd://10.18.28.17/' | awk -F ' ' '{print $3}' | sed s/://g)
lpadmin -x $remove_printer2
remove_printer3=$(lpstat -s | grep 'ipp://10.18.28.17/' | awk -F ' ' '{print $3}' | sed s/://g)
lpadmin -x $remove_printer3
if [ -z $printer01 ]; then
:
else4
remove_printer=$(lpstat -s | grep 'smb://sea22233.internal.company.com/SEC2-Canon' | awk -F ' ' '{print $3}' | sed s/://g)
lpadmin -x $remove_printer4
fi
 
Last edited by a moderator:
In general you do something like the following. Be warned though: bash and other shells are extremely bad for this type of scripting because the script may break if you have printer names containing spaces or other special characters, because the shell expands the variables in line and then evaluates the statement. For example, the for loop below expects $remove_printers to expand to a space-separated list of printers from the grep command so a printer name containing spaces will be split. And a printer name containing "; do" would break the script. In some cases this may even cause security bugs if the script is privileged. So if at all possible use a better scripting languages like Perl which handles quoting more robustly.

Having said that, loops in bash work this way:

remove_printers=$(lpstat -c -v | grep '10.18.28.17' | awk -F ' ' '{print $3}' | sed s/://g)
for printer in $remove_printers ; do
echo remove $printer
done​

I also replaced "lpstat -s" with "lpstat -c -v" to avoid printing a default line which might break the script.
 
  • Like
Reactions: gpchess2k
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.