Linux all console output to file

How to save terminal output to a file under Linux/Unix

H ow do I save the terminal output to a file when using BASH/KSH/CSH/TCSH under Linux, macOS, *BSD or Unix-like operating systems?

Yes, we can save command output by redirecting it to a file. The standard streams for input, output, and error are as follows (also known as file descriptors):

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux, macOS, or Unix
Est. reading time 3 minutes
  1. stdin (numeric value 0) – Keyboard
  2. stdout (numeric value 1) – Screen/display
  3. stderr (numeric value 2) – Screen/display
  • Redirect stdout/stderr to a file
  • Redirect stdout to a stderr OR redirect stderr to a stdout
  • To redirect stderr and stdout to a file
  • We can redirect stderr and stdout to stdout too
  • And finally you can redirect stderr and stdout to stderr

How to save terminal output to a file

By default, the command sends outputs to stdout and can be redirected to the file using the following syntax:
command > filename.txt
For example, save the date command output to a file named mydate.txt, run:
date > mydate.txt
To view file contains use the cat command:
cat mydate.txt

Feed data to our commands (input redirection)

We can read input from a file using the following simple syntax and the file must already exist:
command

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Append output to a file

If the filename.txt/mydate.txt (file) already exists, it will get overwritten. To append output, run:
command >> filename.txt
echo «——————» >> mydate.txt
ls -l /etc/resolv.conf >> mydate.txt
Verify it:
cat mydate.txt

Please note that the file such as mydate.txt is overwritten unless the bash noclobber option is set using the set command. For example, turn off noclobber option:
set -o noclobber
echo «some data» > mydata.txt
Sample outputs:

We can turn on noclobber option as follows:
set +o noclobber
echo «foo bar» > mydata.txt

How to redirect stderr to a file

The syntax is as follows:
command &> file.txt
command &>> file.txt
OR
command 2> file.txt
command 2>> file.txt
Above works with bash and other modern shell. For POSIX version try:
command >output.txt 2>&1
command >>output.txt 2>&1
In this example, send the find command errors to a file named err.log:
find / -iname «*.conf» &>err.log
## OR ##
find / -iname «*.conf» 2>err.log
## POSIX version ##
find . -iname «*.conf» >err.log 2>&1
Verify it:
cat err.log
Sample outputs:

How to suppress error messages

Use the following syntax:
command 2>&-
find . -iname «*.txt» 2>&-
We can also redirect error messages (stderr) to standard output (stdout), run:
command 2>&1
echo «foo» 2>&1
kill $target_pid 2>&1 > /dev/null

How to redirect both stdout and stderr to a file

The syntax is as follows to redirect both stdout and stderr to a file:
command 2>&1 | tee output.txt
For example:
find . -iname «*.txt» 2>&1 | tee cmd.log
cat cmd.log
To append text to end of file use the following syntx:
find . -iname «*.conf» 2>&1 | tee -a cmd.log
cat cmd.log

How to combine redirections

The following command example simply combines input and output redirection. The file resume.txt is checked for spelling mistakes, and the output is redirected to an error log file named err.log:
spell error.log

How to redirect screen output (stdout) and errors (stderr) to /dev/null

Try the following syntax
command > /dev/null 2>&1
/path/to/script.py > /dev/null 2>&1

Redirect both standard error and standard out messages to a log file

command > log.txt 2>&1
/path/to/my-appname.py > my-appname.log 2>&1

Conclusion

You learned how to save terminal output to a file when using Linux or Unix-like operating system with modern shell such as Bash or KSH including POSIX syntax. See bash docs here for more info or type the following man command:
man bash

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

Источник

Linux all console output to file

В данной статье пойдет речь о том, как перенаправить вывод любой команды терминала (консоли) Linux в текстовый файл.

Порой, вывод некоторых терминальных команд может быть огромным. К примеру, список программ, которые могут быть обновлены:

Намного удобнее перенаправить вывод данной команды в текстовый файл и уже просмотреть его с помощью удобного текстового редактора.

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

Прежде чем перейти к обсуждению сохранения вывода команд терминала в файл, немножко теории о стандартных потоках вывода Linux.

Стандартные потоки вывода Linux.

Подробнее о стандартных потоках можно прочитать в Википедии:

Если по существу, то в Linux есть 3 стандартных потока:

  • stdin — поток номер 0, стандартный поток ввода.
  • stdout — поток номер 1, стандартный поток вывода.
  • stderr — поток номер 2, стандартный поток ошибок, диагностических и отладочных сообщений.

Когда мы выполняем какую-либо команду в терминале:

Вывод всех, выполненных команд на скриншоте выше, это stdout — стандартный поток вывода.

А вот вывод стандартного потока ошибок stderr:

Как видно на скриншоте, строки с ошибками начинаются с буквы «E:» (error), а предупреждающая информация c W: (warning).

С определениями, названиями стандартных потоков разобрались. Теперь можно перейти к способам сохранения вывода терминала в файл.

Базовый способ сохранения в файл вывода терминала (консоли) Linux.

Стандартный поток вывода перенаправляется с помощью символа «>», то есть самый простой вариант перенаправления вывода терминала в файл будет выглядеть следующем образом:

то есть, после команды ставим > , в результате чего, вывод команды будет сохранен в файл «название_файла.txt».

Реальный пример команды:

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

Если указать одинарный символ «>», то файл будет постоянно перезаписываться при повторном выполнении команды.

Чтобы новая информация добавлялась в конец файла, а не перезаписывался весь файл, нужно использовать двойной символ «>>». Команда будет выглядеть следующим образом:

Мы перенаправляли стандартный поток вывода в файл, но ошибки у нас отображаются в терминале, а в файл текст ошибки добавлен не будет.

Сейчас я описал самый обычный способ перенаправления стандартного потока вывода stdout в текстовый файл. Теперь разберем другие способы.

8 базовых способов сохранения вывода терминала в файл.

Для большой наглядности я нарисовал табличку:

Список способов:

1. Стандартный поток вывода будет перенаправлен в файл, в терминале виден не будет. Если файл существует, то будет перезаписан.

2. Стандартный поток вывода будет перенаправлен в файл, в терминале виден не будет. Новая информация будет записана в конец существующего файла.

3. Стандартный поток ошибок будет перенаправлен в файл, в терминале виден не будет. Если файл существует, то будет перезаписан.

4. Стандартный поток ошибок будет перенаправлен в файл, в терминале виден не будет. Новая информация будет записана в конец существующего файла.

5. Стандартный поток вывода и стандартный поток ошибок вместе будут перенаправлены в файл, в терминале видны не будет. Если файл существует, то будет перезаписан.

6. Стандартный поток вывода и стандартный поток ошибок вместе будут перенаправлены в файл, в терминале видны не будет. Новая информация будет записана в конец существующего файла.

7. Стандартный поток вывода будет скопирован в файл, в терминале будет по-прежнему виден. Если файл существует, то будет перезаписан.

8. Стандартный поток вывода будет скопирован в файл, в терминале будет по-прежнему виден. Новая информация будет записана в конец существующего файла.

Как вывести полную информацию о компьютере и сохранить эту информацию в html, pdf.

В Linux есть команда, которая выводит всю информацию о компьютере в терминал lshw (от англ. list hardware).
Её нужно запускать с правами суперпользователя sudo:

Но не совсем удобно читать эту информацию в терминале.

У данной команды есть параметр -html, который позволяет вывести данную информацию в html. Теперь, когда мы научились перенаправлять вывод команд терминала в файл, давайте выведем информацию о системе и компьютере в удобно читаемый html файл:

В текущем каталоге создастся html файл, который можно открыть любым, установленным у вас в системе, браузером:

И теперь, если мы хотим сохранить в pdf эту информацию, то выбираем печать (CTRL-P), формат pdf и нажимаем «Печать».

Источник

How to store console output to a file

I am running embedded Linux and my command line has console=/dev/ttyO0.
I have terminal program connected to this UART and can see EVERYTHING produced by the system. Now, when running in the field, I want to store all this output in the file (I have the media connected). But all my efforts using syslogd, klogd, logger and Co. do not give me the desired result — some messages are stored, but some are not — usually the most improtant.
For example, if I run:

«echo» commands I see in syslog, prints from the application too, some drivers messages too. But if the application crashes with segmentation fault this info is not logged. But this is most valuable!
So, the best and most desired is to redirect ttyO0 to a file, but how?
I found such a recommendation:

but this doesn’t work: I can type a command, f.e. ifconfig, but reply does not appear neither in the file nor on console. Even the file is not created. -(
If it is possible to have both — file and serial console — it will be brilliant. But file has higher priority.

Many thanks for a help!

UPDATE: I found the answer — see the last one.

3 Answers 3

You seem to have missed one fairly basic fact. Every pipeable program relies on the fact that it gets three standard file descriptors in a pre-opened state from whatever program invokes it. In most cases involving pipes, the invoking program will be the command shell.

These three file descriptors are:

  • file descriptor #0: standard input stream, or stdin for short.
  • file descriptor #1: standard output stream, or stdout for short.
  • file descriptor #2: standard error output stream, or stderr for short.

When a program is not being piped or redirected to read/write a file, then all these three file descriptors will usually point to a TTY device the current login session is running on. If a program is deliberately started as a daemon or a background/non-interactive process, all of these might be directed to file(s) or /dev/null , or possibly into some sort of logging facility.

Error messages are normally output into the stderr stream, precisely so that they won’t get mixed in with the possibly-piped data output. But in cases like your, when you wish to capture all the output, you need to explicitly tell the system to grab both streams.

If you want to pass all the output from your myapplication.sh into a pipe, you might have to do something like this:

The 2>&1 says «redirect file descriptor #2 to the same place #1 is going», and then you can pipe both of them at once.

You can test it yourself with a little script like this:

The >&2 means «take the standard output of this command and send it into the standard error stream instead». This is probably the easiest way to generate stderr output in a script.

Now, if you run this script like ./test.sh | od -t x1z to get its output in hex-dumped form, you’ll get this:

So only the stdout output got processed by the od command.

If you add the 2>&1 to merge both streams, you’ll get this instead:

Now both outputs were sent into the pipeline, which is what you want in your case with | logger .

Your second command line is capturing whatever your embedded device is receiving from the terminal program, not what the embedded device is sending to the terminal:

You said you’re working on an embedded system that uses the kernel parameter console=/dev/ttyO0 , so essentially /dev/console will be a serial port, not a graphical display (which may not even exist in an embedded device).

If you are running that command on the embedded device, the commands inside the parentheses will run with their standard input stream (file descriptor #0, or stdin for short) assigned to /dev/ttyO0 . But if you are entering that command over the serial line connected to ttyO0 , that’s what it’s probably going to be by default, so this input redirection may just be re-enforcing the situation as it is.

The /dev/ttyO0 device is the direct representation of the UART that is connected to your terminal program on the other computer. When you read from it, you get only what you are typing into the terminal program: there is no way to read back any output that was previously sent into it. And anything written into it goes directly to the terminal program at the end of the serial cable.

The Unix command line on a serial port normally works on a remote echo principle: in order to see what you are writing on the terminal program, the TTY driver on the embedded system must send a copy of every character you type right back to the terminal program. This behavior is not symmetric: the terminal program will not be also sending back a copy of anything it receives over the serial port connection.

The TTY driver is a complicated thing, because Unix heritage requires it to be capable of doing a lot of things — the remote echo feature is just one of them.

When you use stty raw , you’re effectively switching off all the normally-helpful features of the TTY driver, including the remote echo feature. So, from that point onwards, unless something explicitly reads from /dev/ttyS0 and writes it immediately right back into it, you won’t see what you are writing on the terminal program.

Once the stty raw command has exited, any input from the terminal program will go into the cat command, which would just pass it into its standard output as-is when invoked with no parameters. But its standard output has now been redirected into a file, received.txt . So what happens is that only what you’re typing on the terminal program gets written into the file until the cat command ends — and it only ends when it gets the end-of-file character (typically Control+D ).

(Because of whatever buffering might be done by the shell doing the redirection, there might be no output into the received.txt file unless you end your typing with the end-of-file character, and/or type more than one line of text.)

So, other than switching off the TTY driver features, the (stty raw; cat > received.txt) on the embedded system does nothing at all to capture any output that is being written into /dev/ttyO0 . The only use for this command would be when you’re troubleshooting the serial port connection: if you are suspicious that your terminal program is somehow mangling the characters you’re sending out, this is the way to capture whatever the terminal program is sending to the embedded device in its most raw form.

If you want to record absolutely everything that happens over the UART connection, including e.g. kernel panic messages, then the best way to do it would probably be to tell your terminal program on the other computer to log all the traffic. Many terminal programs have this feature built-in.

This is because if something is going wrong with the kernel, it might not be actually possible to write anything into a disk file any more. It’s much simpler to just send the error message text out of an UART and trust that whoever is receiving it will catch it.

Источник

Читайте также:  Проблемы при запуске линукс
Оцените статью