Bash script question - variable as a list?

ChrisTech
Contributor

We're transitioning over to a new printing system and I need to remove printers on all macOS machines. The printers are all named by site, for example Miami HP 504, Dallas HP 653 etc. 

What's a good way to delete the printers in bulk by using the site names? I have a script that works for one site at a time. I don't want to just remove all printers as there may be personal printers installed. 

7 REPLIES 7

jamf-42
Valued Contributor II

bash arrays would be the answer maybe? 

https://linuxhandbook.com/bash-arrays/

howie_isaacks
Valued Contributor II

This may work. I was playing around with using a for loop. It just deleted the printers from my Mac. You would add at list of your printer names to the "printers" variable.

#!/bin/zsh

printers=("Printer1" "Printer2")

for printer in ${printers[@]}; do
	/usr/sbin/lpadmin -x "$printer" 
done

 

jamf-42
Valued Contributor II

yup.. that works and if there are 'a lot' you could always pull in the list from a CSV

howie_isaacks
Valued Contributor II

I'm curious how you would do this from a CSV. I think I know how and when I have time I will try it later.

jamf-42
Valued Contributor II

foo=$(cat path/to/text.csv)

ChrisTech
Contributor

I ended up doing:

#!/bin/bash

lpstat -a | cut -d " " -f1 | grep "Miami_" | while read MIAMI
do
echo "-- Miami printers detected attempting to delete:" $MIAMI
lpadmin -x $MIAMI
sleep 1
done

 

and just repeat for each site . . .

dlondon
Valued Contributor

You could potentially make a loop around what you've done there Chris and then use a Here Doc.  Here's an example script for Here Doc's

#!/bin/bash
# here_doc_test.bash

SITES=$(cat <<EOF
Miami_
Orlando_
Austin_ 
Phoenix_
EOF
)

echo $SITES

for i in $SITES
do
	echo $i
done