Print from command line
How can I print the command line output directly to the printer. I am using ubuntu server 12.04 and I have to copy files into a shared directory and then download them from a desktop ubuntu distribution to print them. Any help is appreciated
You didn’t say if you’ll be printing plain text or PDF. Some systems only support plain text out of the box, so this needs to be covered.
8 Answers 8
Mainly there are two default commands:
lpr submits files for printing. Files named on the command line are sent to the named printer (or the default destination if no destination is specified). If no files are listed on the command-line, lpr reads the print file from the standard input.
lp submits files for printing or alters a pending job. Use a filename of «-» to force printing from the standard input.
so easily use the command:
man firefox | lp -d printername
This will print the man page from firefox to the specified printer
Thanks, I also needed to use o fit-to-page to keep the text on the page a bit better. man bash | lp -o media=letter -o portrait -o fit-to-page — , the — at the end ensures standard input is read.
If your printer is default you don’t need the -d parameter. On Ubuntu with Unity, the default printer is set by clicking on the Search button then type «print» and it will take you to the right place where the default can be set. Also, lp in the example says you have been around Unix for some time. lpr works the same on Ubuntu.
If you have them installed, another pair of options worth knowing about are
These are useful for providing numbered pages with headings and optional line-numbers. You can also use then to print booklet style (e.g. two pages on each side of a sheet)
I use these with Postscript-capable printers but I believe that Ubuntu’s print system can rasterize PS for any supported printer.
You may want to find out how the printer is accessed first — lpstat will give you that information. If you compare its output across both systems, you can probably tell whether the printer in question has been configured on both of them. lpstat -p -d lists all printers with their status and tells which one has been set as default printer.
You can simply pipe your output to the lp or lpr command then. You may want to insert a filter for pretty-printing or pagination though. There’s a good summary of tools at the debian manual «Highlighting and formatting plain text data», but I’m usually just using sed to highlight prompts and other stuff before sending everything through a2ps
To print a .txt file in a use :
command | lpr -P printername -p ( periority from 1 to 100 )
ls -l | lpr -P printername -p 1
You can use the lp command.
To print the output of a command to the default printer (use lpstat -d to see what the default printer is):
To print to a specific printer (use lpstat -p | awk » to list available printer names):
echo "test" | lp -d printername
To print a file, rather than a command output:
The question is about how to print from the command line on a server, and it sounds like you don’t yet have any printers defined on that system. I don’t have a system to check on so the following are approximate, but they should give you the general idea:
- Make sure the CUPS system is installed and running. It provides the daemons that will handle your print jobs.
- Once this is up, you need to set up one or more network printers to print to. The usual way to install printers is with the Printer Admin utility, but you evidently aren’t set up to run any GUI programs from your server— just commandline access via ssh. Since you already have an Ubuntu desktop system on the same network, I’d try copying the contents of the directory /etc/cups from the desktop box to the server. It should contain all the printer definitions and drivers you need. Check the files for any necessary adjustments (in case your set-up mentions user IDs or passwords that differ between the two systems), restart cupsd , and if you’re lucky you’ll be able to use lpr to print from the commandline.
PS. In a pinch, you could install enough X utilities to run the Print Admin GUI utility via a remote X connection to your desktop Ubuntu box (log in with ssh -X ), and define the printers you need. But hopefully this won’t be necessary.
Печать файлов из командной строки Linux
Очень часто, разбирая в Терминале содержимое того или иного конфигурационного файла Linux, возникает желание распечатать его на бумаге. Совсем не обязательно копировать содержимое файла в OpenOffice и потом отправлять его на печать. Достаточно воспользоваться командой lp, входящей в состав каждого дистрибутива Linux.
Для примера, попробуем вывести на печать содержимое одного из важных конфигурационных файлов ОС Linux — /etc/fstab. Для этого выполним команду:
Достав полученное из принтера, мы увидим, что содержимое файла распечаталось, но имеет весьма неприглядный вид — у документа получились строки разной длины (отсутствует форматирование). Для того, чтобы придать документу более читаемый вид, вместе с командой lp используем параметр -o page-top=, который позволит нам назначить определенную ширину строк.
мы получим распечатанный документ, в котором ширина строки будет равна 70 символам.
Если вам необходимо распечатать несколько копий документа, используйте вместе с командой lp параметр -n, который задает количество копий при печати (от 1 до 100):
Иногда бывает удобно сделать так, чтобы система отправляла вам на e-mail сообщение о успешном завершении задания. Для этого воспользуемся параметром -m, который выполняет вышеуказанное действие.
lp -o page-top=70 -n 3 -m user@localhost /etc/fstab
Возможно, что при использовании команды lp и отправке на печать вы увидите ошибку «lp: Ошибка — нет доступного назначения по умолчанию.»:
Это означает, что у вас в Linux не определен принтер по умолчанию. Исправить это можно выполнив следующие действия:
Выберите Система — Параметры — Принтер по умолчанию.
Откроется окно, в котором вам следует выделить курсором необходимый принтер и нажать на кнопку «Использовать по умолчанию»(обведено красным):
После этого пробуйте выполнить команду lp с необходимыми вам параметрами.
IT-поддержка
Оказываем квалифицированную помощь в поддержке Вашей IT-инфраструктуры
Linux lpr command
On Unix-like operating systems, the lpr command submits print jobs.
Description
lpr submits files for printing. Files named on the command line are sent to the named printer (or the default destination if no destination is specified). If no files are listed on the command-line, lpr reads the print file from the standard input.
Printing in Linux
The simplest way to print in Linux is to cat a file to the printing device, like this:
sudo cat my-file-to-print.txt > /dev/lp
What this command does is read the file my-file-to-print.txt and send it, byte by byte, to the printer device /dev/lp. This name is a symbolic link to the device, and may vary. Your printer may be another device name, for instance lp0. Normally cat sends its output to standard output (the terminal) but here we redirect it to the device /dev/lp with the > operator. Only the superuser can write directly to the printer device, which is why we have to preface the command with sudo.
lpr is more user-friendly than this, however, and it lets you queue print jobs. And most importantly, it lets you access the printer device without being the superuser.
Installing lpr, lpd, and CUPS
The way lpr works, in a nutshell, is: it reads in the file and hands the printable data over to the linux printing daemon, lpd. lpd is a legacy piece of software for Linux, but it is supported under the modern system used by most Linux distributions, CUPS (the Common Unix Printing System).
You may need to manually install CUPS, and lpr itself, to print this way. If you’re operating Debian, or a Debian-derived Linux system like Ubuntu that uses the APT package managements system, you can install them by running the following command:
sudo apt-get update && sudo apt-get install cups cups-client lpr
This command will install the Common Unix Printing System on your system. You can now set up CUPS by directing any web browser to the address: http://localhost:631
Doing so opens a web-based CUPS configuration screen, which should look something like this:
Then, from the command line, add your user to the group lpadmin with the command:
This command adds you to the group of users allowed to administer printers on your system. Now go back to the CUPS web administration panel, and under the administration tab, select «Add Printer.» You will be prompted for your username and password, and can set up a new printer.
Syntax
lpr [ -E ] [ -H server[:port] ] [ -U username ] [ -P destination[/instance] ] [ -# num-copies [ -h ] [ -l ] [ -m ] [ -o option[=value] ] [ -p] [ -q ] [ -r ] [ -C/J/T title ] [ file(s) ]
Options
-E | Forces encryption when connecting to the server. |
-H server[:port] | Specifies an alternate server. |
-C «name« |
Examples
Submits a request to print the file myfile.txt.
cat a file (myfile.txt), piping the output to lpr, which reads its contents from standard input and sends it to the print daemon for printing.
Print 3 copies of myfile.txt.
Related commands
hostname — Set or print the hostname of system.
lp — Print a file on the System V operating system.
lpc — Control line printers.
lpq — List the status of available printers.
lprm — Remove requests from the print queue.
lpstat — List the status of the LP print services.
mail — Read, compose, and manage mail.