83

The lpr man page says a destination printer can be specified with the -P flag.

-P destination[/instance]
    Prints files to the named printer.

I have 'added' various printers on local Samba shares using the GUI in Ubuntu/Gnome. How can I get a list of these available printers in the format that the -P flag expects (preferably from a bash shell)?

Kevin Panko
  • 7,346
  • 22
  • 44
  • 53
Ian Mackinnon
  • 5,606
  • 5
  • 29
  • 33

2 Answers2

124
$ lpstat -p -d

From the CUPS manual.

The -p option specifies that you want to see a list of printers, and the -d option reports the current default printer or class.

mwfearnley
  • 7,172
  • 5
  • 26
  • 38
Kevin Panko
  • 7,346
  • 22
  • 44
  • 53
19

To get a list you can use:

lpstat -a

or

cat /etc/printcap

To print only the printer names:

lpstat + read + array:

$ while read l; do l=($l); echo "${l[0]}"; done <<< "$(lpstat -a)"

lpstat + awk:

$ lpstat -a | awk '{print $1}'

lpstat + cut:

$ lpstat -a | cut -f1 -d ' '

cat + grep + cut in /etc/printcap:

$ cat /etc/printcap | cut -f1 -d'|' | grep '^#' -v

This is what is shown, one per line:

HP_LaserJet_P1606dn
HP_Deskjet_2540_series
HP_LaserJet_M1212nf
GCP-Save_to_Google_Docs

I feel like the lpstat solutions are more elegant and reliable. Mostly because /etc/printcap was not found on some systems I tested.

About using awk or cut, depends on what you have installed and prefer. The bash read + bash array option should work on any bash shell without the need for externals.

EDIT : I said the marked solution does no work for me on Amazon Linux. But I guess it works if you just want to copy the printer names from the middle of the rest of the output. Works the same as using just lpstat -a.

$ lpstat -p -d
printer HP_Deskjet_2540_series is idle. enabled since Tue 22 Dec 2015 01:12:10 PM BRST
. . .
printer GCP-Save_to_Google_Docs is idle. enabled since Tue 15 Dec 2015 02:13:33 AM BRST
system default destination: HP_LaserJet_P1606dn
Gus Neves
  • 439
  • 4
  • 6
  • lpstat + cut will work on OS X as well. – tresf Mar 22 '16 at 16:58
  • According to your output sample, `lpstat -p -d` seems to work… – Skippy le Grand Gourou Feb 08 '17 at 12:48
  • Sorry, but he asks `How can I get a list of these available printers in the format that the (lpr) -P flag expects`. My example of `lpstat -p -d` clearly shows that you get more than just the printer name with that. On which case you cannot use that output for a `lpr -P $PRINTERNAME` call. So, no! `lpstat -p -d` does not work in the example I gave. – Gus Neves Apr 22 '17 at 00:33