Linux redirect output to file and console

How to redirect output to a file and stdout

In bash, calling foo would display any output from that command on the stdout. Calling foo > output would redirect any output from that command to the file specified (in this case ‘output’). Is there a way to redirect output to a file and have it display on stdout?

If someone just ended up here looking for capturing error output to file, take a look at — unix.stackexchange.com/questions/132511/…

A note on terminology: when you execute foo > output the data is written to stdout and stdout is the file named output . That is, writing to the file is writing to stdout. You are asking if it is possible to write both to stdout and to the terminal.

@WilliamPursell I’m not sure your clarification improves things 🙂 How about this: OP is asking if it’s possible to direct the called program’s stdout to both a file and the calling program’s stdout (the latter being the stdout that the called program would inherit if nothing special were done; i.e. the terminal, if the calling program is an interactive bash session). And maybe they also want to direct the called program’s stderr similarly («any output from that command» might be reasonably interpreted to mean including stderr).

If we have multiple commands that want to pipe outputs, use ( ) . For example (echo hello; echo world) | tee output.txt

11 Answers 11

The command you want is named tee :

For example, if you only care about stdout:

If you want to include stderr, do:

program [arguments. ] 2>&1 | tee outfile 

2>&1 redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the tee command.

Furthermore, if you want to append to the log file, use tee -a as:

program [arguments. ] 2>&1 | tee -a outfile 

If OP wants «all output» to be redirected, you’ll also need to grab stderr: «ls -lR / 2>&1 | tee output.file»

@evanmcdonnal The answer is not wrong, it just may not be specific enough, or complete depending on your requirements. There certainly are conditions where you might not want stderr as part of the output being saved to a file. When I answered this 5 years ago I assumed that the OP only wanted stdout, since he mentioned stdout in the subject of the post.

Ah sorry, I might have been a little confused. When I tried it I just got no output, perhaps it was all going to stderr.

Use -a argument on tee to append content to output.file , instead of overwriting it: ls -lR / | tee -a output.file

If you’re using $? afterwards it will return the status code of tee , which is probably not what you want. Instead, you can use $ .

$ program [arguments. ] 2>&1 | tee outfile 

2>&1 dumps the stderr and stdout streams. tee outfile takes the stream it gets and writes it to the screen and to the file «outfile».

Читайте также:  Ubuntu with linux приложения

This is probably what most people are looking for. The likely situation is some program or script is working hard for a long time and producing a lot of output. The user wants to check it periodically for progress, but also wants the output written to a file.

The problem (especially when mixing stdout and stderr streams) is that there is reliance on the streams being flushed by the program. If, for example, all the writes to stdout are not flushed, but all the writes to stderr are flushed, then they’ll end up out of chronological order in the output file and on the screen.

It’s also bad if the program only outputs 1 or 2 lines every few minutes to report progress. In such a case, if the output was not flushed by the program, the user wouldn’t even see any output on the screen for hours, because none of it would get pushed through the pipe for hours.

Update: The program unbuffer , part of the expect package, will solve the buffering problem. This will cause stdout and stderr to write to the screen and file immediately and keep them in sync when being combined and redirected to tee . E.g.:

$ unbuffer program [arguments. ] 2>&1 | tee outfile 

Источник

Command output redirect to file and terminal [duplicate]

I am trying to throw command output to file plus console also. This is because i want to keep record of output in file. I am doing following and it appending to file but not printing ls output on terminal.

3 Answers 3

Yes, if you redirect the output, it won’t appear on the console. Use tee .

In this case error is merged into the output ( 2>&1 ), so the next process consuming the pipe will see both of them as regular input (in short: yes).

How to give the size of ls.txt file in above command so that it does not exceeds that given size. And once it exceeds max size, how to create a new file in that same directory (for eg: ls1.txt,ls2.txt. )

Be aware that you will loose the exit status of ls . If you want to retain the exit status of ls , or more precisely want to figure out if something in your pipe failed despite tee being the last (and very likely successful) command in your pipe, you need to use set -o pipefail .

It is worth mentioning that 2>&1 means that standard error will be redirected too, together with standard output. So

someCommand | tee someFile 

gives you just the standard output in the file, but not the standard error: standard error will appear in console only. To get standard error in the file too, you can use

someCommand 2>&1 | tee someFile 

(source: In the shell, what is » 2>&1 «? ). Finally, both the above commands will truncate the file and start clear. If you use a sequence of commands, you may want to get output&error of all of them, one after another. In this case you can use -a flag to «tee» command:

someCommand 2>&1 | tee -a someFile 

Источник

Перенаправление ввода вывода Linux

Одна из самых интересных и полезных тем для системных администраторов и новых пользователей, которые только начинают разбираться в работе с терминалом — это перенаправление потоков ввода вывода Linux. Эта особенность терминала позволяет перенаправлять вывод команд в файл, или содержимое файла на ввод команды, объединять команды вместе, и образовать конвейеры команд.

Читайте также:  Linux copy all files to usb

В этой статье мы рассмотрим как выполняется перенаправление потоков ввода вывода в Linux, какие операторы для этого используются, а также где все это можно применять.

Как работает перенаправление ввода вывода

Все команды, которые мы выполняем, возвращают нам три вида данных:

  • Результат выполнения команды, обычно текстовые данные, которые запросил пользователь;
  • Сообщения об ошибках — информируют о процессе выполнения команды и возникших непредвиденных обстоятельствах;
  • Код возврата — число, которое позволяет оценить правильно ли отработала программа.

В Linux все субстанции считаются файлами, в том числе и потоки ввода вывода linux — файлы. В каждом дистрибутиве есть три основных файла потоков, которые могут использовать программы, они определяются оболочкой и идентифицируются по номеру дескриптора файла:

  • STDIN или 0 — этот файл связан с клавиатурой и большинство команд получают данные для работы отсюда;
  • STDOUT или 1 — это стандартный вывод, сюда программа отправляет все результаты своей работы. Он связан с экраном, или если быть точным, то с терминалом, в котором выполняется программа;
  • STDERR или 2 — все сообщения об ошибках выводятся в этот файл.

Перенаправление ввода / вывода позволяет заменить один из этих файлов на свой. Например, вы можете заставить программу читать данные из файла в файловой системе, а не клавиатуры, также можете выводить ошибки в файл, а не на экран и т д. Все это делается с помощью символов » и «>».

Перенаправить вывод в файл

Все очень просто. Вы можете перенаправить вывод в файл с помощью символа >. Например, сохраним вывод команды top:

Опция -b заставляет программу работать в не интерактивном пакетном режиме, а n — повторяет операцию пять раз, чтобы получить информацию обо всех процессах. Теперь смотрим что получилось с помощью cat:

Символ «>» перезаписывает информацию из файла, если там уже что-то есть. Для добавления данных в конец используйте «>>». Например, перенаправить вывод в файл linux еще для top:

По умолчанию для перенаправления используется дескриптор файла стандартного вывода. Но вы можете указать это явно. Эта команда даст тот же результат:

Перенаправить ошибки в файл

Чтобы перенаправить вывод ошибок в файл вам нужно явно указать дескриптор файла, который собираетесь перенаправлять. Для ошибок — это номер 2. Например, при попытке получения доступа к каталогу суперпользователя ls выдаст ошибку:

Вы можете перенаправить стандартный поток ошибок в файл так:

ls -l /root/ 2> ls-error.log
$ cat ls-error.log

Чтобы добавить данные в конец файла используйте тот же символ:

Перенаправить стандартный вывод и ошибки в файл

Вы также можете перенаправить весь вывод, ошибки и стандартный поток вывода в один файл. Для этого есть два способа. Первый из них, более старый, состоит в том, чтобы передать оба дескриптора:

Сначала будет отправлен вывод команды ls в файл ls-error.log c помощью первого символа перенаправления. Дальше в тот же самый файл будут направлены все ошибки. Второй метод проще:

Также можно использовать добавление вместо перезаписи:

Стандартный ввод из файла

Большинство программ, кроме сервисов, получают данные для своей работы через стандартный ввод. По умолчанию стандартный ввод ожидает данных от клавиатуры. Но вы можете заставить программу читать данные из файла с помощью оператора «:

Вы также можете сразу же перенаправить вывод тоже в файл. Например, пересортируем список:

Таким образом, мы в одной команде перенаправляем ввод вывод linux.

Использование тоннелей

Можно работать не только с файлами, но и перенаправлять вывод одной команды в качестве ввода другой. Это очень полезно для выполнения сложных операций. Например, выведем пять недавно измененных файлов:

Читайте также:  Yandex disk linux deb

С помощью утилиты xargs вы можете комбинировать команды таким образом, чтобы стандартный ввод передавался в параметры. Например, скопируем один файл в несколько папок:

echo test/ tmp/ | xargs -n 1 cp -v testfile.sh

Здесь параметр -n 1 задает, что для одной команды нужно подставлять только один параметр, а опция -v в cp позволяет выводить подробную информацию о перемещениях. Еще одна, полезная в таких случаях команда — это tee. Она читает данные из стандартного ввода и записывает в стандартный вывод или файлы. Например:

echo «Тест работы tee» | tee file1

В сочетании с другими командами все это может использоваться для создания сложных инструкций из нескольких команд.

Выводы

В этой статье мы рассмотрели основы перенаправления потоков ввода вывода Linux. Теперь вы знаете как перенаправить вывод в файл linux или вывод из файла. Это очень просто и удобно. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Redirect all output to file in Bash [duplicate]

I know that in Linux, to redirect output from the screen to a file, I can either use the > or tee . However, I’m not sure why part of the output is still output to the screen and not written to the file. Is there a way to redirect all output to file?

9 Answers 9

That part is written to stderr, use 2> to redirect it. For example:

foo > stdout.txt 2> stderr.txt 

or if you want in same file:

Note: this works in (ba)sh, check your shell for proper syntax

well, i found the reference and have deleted my post for having incorrect information. from the bash manual: ‘»ls 2>&1 > dirlist» directs only the standard output to dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist» 🙂

also from the bash man «There are two formats for redirecting standard output and standard error: &>word and >&word Of the two forms, the first is preferred. This is semantically equivalent to >word 2>&1»

Two important addenda: If you want to pipe both stdout and stderr, you have to write the redirections in the opposite order from what works for files, cmd1 2>&1 | cmd2 ; putting the 2>&1 after the | will redirect stderr for cmd2 instead. If both stdout and stderr are redirected, a program can still access the terminal (if any) by opening /dev/tty ; this is normally done only for password prompts (e.g. by ssh ). If you need to redirect that too, the shell cannot help you, but expect can.

All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with > , >> , or | . stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:

EDIT: thanks to Zack for pointing out that the above solution is not portable—use instead:

If you want to silence the error, do:

Источник

Оцените статью
Adblock
detector