bash redirect stderr to stdout

Как перенаправить stderr на stdout в Bash

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

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

Дескриптор файла — это просто число, представляющее открытый файл.

Входной поток предоставляет информацию программе, как правило, путем ввода с клавиатуры.

Выходные данные программы попадают в стандартный поток ввода, а сообщения об ошибках — в стандартный поток ошибок. По умолчанию на экран выводятся потоки ввода и ошибки.

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

Перенаправление — это способ захватить вывод программы и отправить его в качестве ввода в другую программу или файл.

Чтобы перенаправить стандартную ошибку ( stderr ), используйте оператор 2> :

Вы можете записать как stderr и stdout в два отдельных файла:

Чтобы сообщения об ошибках не отображались на экране, перенаправьте stderr на /dev/null :

Перенаправление stderr на stdout

При сохранении вывода программы в файл довольно часто перенаправляют stderr на stdout чтобы у вас было все в одном файле.

Чтобы перенаправить stderr на stdout и отправлять сообщения об ошибках в тот же файл, что и стандартный вывод, используйте следующее:

Выводы

Понимание концепции перенаправлений и файловых дескрипторов очень важно при работе в командной строке.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

BASH Shell Redirect stderr To stdout ( redirect stderr to a File )

Understanding I/O streams numbers

The Unix / Linux standard I/O streams with numbers:

Tutorial requirements
RequirementsUnix or Linux with bash
Root privilegesNo
DifficultyEasy
Est. reading time6 mintues
HandleNameDescription
0stdinStandard input
1stdoutStandard output
2stderrStandard error

Redirecting output

Redirecting the standard error stream to a file

Redirecting the standard error (stderr) and stdout to file

Redirecting stderr to stdout to a file or another command

Redirect stderr to stdout

How to redirect stderr to stdout in Bash script

A sample shell script used to update VM when created in the AWS/Linode server:

Our last example uses the exec command and FDs along with trap and custom bash functions:

Want both stderr and stdout to the terminal and a log file too?

Try the tee command as follows:
command1 2>&1 | tee filename
Here is how to use it insider shell script too:

Conclusion

In this quick tutorial, you learned about three file descriptors, stdin, stdout, and stderr. We can use these Bash descriptors to redirect stdout/stderr to a file or vice versa. See bash man page here:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Comments on this entry are closed.

What this mean?
$ command > file-name 2>&1

This means redirect stdout to file-name, with that in mind redirect stderr t stdout.
This will lead to both stderr and stdout go to file-name.

Sayed: that line means execute the command while redirecting both stdout and stderr to a file given by file-name.

A slightly more correct is:
The output of the ‘command’ is redirected to a ‘file-name’ and the error chanel (that is the ‘2’ is redirected to a pointer (?) of the output (‘&1’).
So stderr goes to the stdout and that goes to the file.

Actually it means “first redirect STDERR to STDOUT, so any errors printed out on STDERR should go to STDOUT. Then, execute ‘command’ and redirect its STDOUT to ‘file-name’” – keeping in mind that at this point STDOUT will also contain whatever is written to STDERR because of the earlier redirection.

Incorrect.
There are two incorrect concepts in your answer.

First is: the redirection happens from left to right. This means that the STDOUT is redirected first.
(When you have > without a stream number, it actually have an implicit 1)
And only after STDERR is redirected to “the same place STDOUT is pointing”, meaning, ‘file-name’

Second wrong concept with your answer is: There are no connection between the descriptors. Changing STDOUT after STDERR had been redirected to STDOUT won’t change STDERR.
It will make STDERR point to STDOUT and then change STDOUT to something else (without touching STDERR)
Here is a more detailed tutorial covering both those misconceptions
http://wiki.bash-hackers.org/howto/redirection_tutorial

I like the &>file one. but not for every stiuation.

In pre-bash4 days you HAD to do it this way:

cat file > file.txt 2>&1

now with bash 4 and greater versions… you can still do it the old way …but …

The above is bash4+ … some OLD distros may use prebash4 but I think they are alllong gone by now. Just something to keep in mind.

I really love: “ command2>&1 | tee logfile.txt

Hi! good explanation, I’d like to make a function on C that redirects STDIN and SDTOUT to an script, how can I do that, I mean, the exist a library’s on C to put terminal sintaxis on C?, how would you start to do it? I’m very lost with this. Thankyou!

Источник

Потоки данных

bash redirect stderr to stdoutСтатья посвящена работой с потоками данных в bash. Я постарался написать ее наиболее доступным и простым языком, чтобы было понятно даже новичкам в Linux.

В одной из моих статей мы рассматривали запись звука в файл с помощью команды:

Эта команда читает файл (устройство) /dev/audio с помощью команды cat и перенаправляет информацию из него в файл /tmp/my.sound (с помощью оператора >).

У каждой программы существует 3 системных потока: stdout, stderr, stdin.

stdout

Стандартный поток вывода данных для программ. Например, когда мы пишем команду ls, то список папок и файлов она выводит именно в этот поток, который отображается у нас в консоли:

stderr

Поток вывода ошибок. Если программа не смогла сделать все как надо — она пишет именно в этот поток. Например, когда rm пытается удалить несуществующий файл:

$ rm example.txt
rm: example.txt: No such file or directory

stdin

Поток ввода данных. А вот это довольно интересный и удобный поток. Например, его использует вэб-сервер, когда просит интерпретаторы выполнить скрипты через CGI. Мы тоже можем попробовать:

В этом примере мы встретили оператор перенаправления потока вывода. Мы остановимся на нем позже.

Перенаправление потоков

Для начала рассмотрим перенаправление потоков в файлы, устройства и другие потоки.

В этом примере мы направили stdout команды ls в файл 1.txt. Читаем его:

Да, все успешно записалось.

Теперь попробуем направить stderr команды rm:

Здесь мы использовали номер потока stderr (2). По умолчанию оператор > перенаправляет поток stdout, который имеет номер 1. Чтобы направить другой поток, надо перед оператором > поставить его номер.

Мы можем направлять одни потоки в направлении других:

В этом примере мы направили поток stdout в файл 1.txt, а затем направили stderr туда же, куда направлен stdout с помощью оператора & перед номером потока.

Теперь давайте поиграем с потоком stdin. Например, я хочу найти все папки «.svn» в некотором проекте и удалить:

Команда find с параметром. выводит в stdout все вложенные папки и файлы, которые находит в данной папке и во всех вложенных.

Теперь нам надо выбрать только папки с именем «.svn»:

Оператор | перенаправляет stdout одного приложения в stdin следующего. То есть все строки найденные с помощью find пошли в команду grep, которая выбирает строки по определенным условиям и выводит их. Здесь условие — это регулярное выражение, которое говорит о том, что строка должна заканчиваться на «/.svn».

Нужные папки мы выбрали, осталось их удалить.

И снова новый оператор: `. Он забирает stdout из команды, которую он окружает и вставляет в данное место как строку.

Получается, что мы запросили все файлы, выбрали из них папки с именем «.svn» и отдали результат как аргументы команде rm. В этом случае у нас будут проблемы если имена файлов и папок содержат пробелы. Исправляем ситуацию:

Источник

Redirect stderr and stdout in Bash [duplicate]

I want to redirect both standard output and standard error of a process to a single file. How do I do that in Bash?

bash redirect stderr to stdout

15 Answers 15

Take a look here. It should be:

It redirects both standard output and standard error to file filename.

bash redirect stderr to stdout

This is going to redirect standard error to standard output and standard output to some_file and print it to standard output.

bash redirect stderr to stdout

You can redirect stderr to stdout and the stdout into a file:

To the author of the original post,

It depends what you need to achieve. If you just need to redirect in/out of a command you call from your script, the answers are already given. Mine is about redirecting within current script which affects all commands/built-ins (includes forks) after the mentioned code snippet.

So, from the beginning. Let’s assume we have a terminal connected to /dev/stdout (file descriptor #1) and /dev/stderr (file descriptor #2). In practice, it could be a pipe, socket or whatever.

The result of running a script having the above line and additionally this one:

If you want to see clearer picture, add these two lines to the script:

bash redirect stderr to stdout

Note: The order matters as liw.fi pointed out, 2>&1 1>file.log doesn’t work.

bash redirect stderr to stdout

Curiously, this works:

But this gives a syntax error:

Short answer: Command >filename 2>&1 or Command &>filename

Consider the following code which prints the word «stdout» to stdout and the word «stderror» to stderror.

Note that the ‘&’ operator tells bash that 2 is a file descriptor (which points to the stderr) and not a file name. If we left out the ‘&’, this command would print stdout to stdout, and create a file named «2» and write stderror there.

Now, we can explain why the solution why the following code produces no output:

To test if you really understand the concept, try to guess the output when we switch the redirection order:

Finally, I’d note that there is a simpler way to do this:

Finally have a look at these great resources:

Источник

Redirecting bash stdout/stderr to two places?

This one’s been bugging me for a while now. Is it possible to redirect stdout and stderr to both the terminal output and to a program?

bash redirect stderr to stdout

3 Answers 3

You can use a named pipe, which is intended for exactly the situation you describe.

Is it possible to redirect stdout and stderr to both the terminal output and to a program?

I’m not sure how useful it is to combine stdout and stderr on the input to an editor, but does omething like this do what you need?

I don’t actually know whether TextMate can take a file to edit as its standard input, that seems a little bizarre. I suspect you would want to send the stdout/stderr to a file and edit it there, in which case you need:

Then, once the process has finished, the editor is called up on the temporary file.

If it can accept standard input for editing, use:

bash redirect stderr to stdout

Not the answer you’re looking for? Browse other questions tagged bash redirect or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *