- How to save terminal output to a file under Linux/Unix
- How to save terminal output to a file
- Feed data to our commands (input redirection)
- Append output to a file
- How to redirect stderr to a file
- How to suppress error messages
- How to redirect both stdout and stderr to a file
- How to combine redirections
- How to redirect screen output (stdout) and errors (stderr) to /dev/null
- Redirect both standard error and standard out messages to a log file
- Conclusion
- How to write the output into the file in Linux
- How do I save terminal output to a file?
- Writing the output into the file
- Appending the output or data to the file
- How to save the output of a command to a file in bash using tee command
- Examples
- I/O redirection summary for bash and POSIX shell
- Conclusion
- Command output to text file linux
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 |
- stdin (numeric value 0) – Keyboard
- stdout (numeric value 1) – Screen/display
- 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
Источник
How to write the output into the file in Linux
How do I save terminal output to a file?
A command can receive input from a file and send output to a file.
Writing the output into the file
The syntax is
command > filename
For example, send output of the ls command to file named foo.txt
$ ls > foo.txt
View foo.txt using the cat command:
$ cat foo.txt
Please note that when you type ‘ls > foo.txt’, shell redirects the output of the ls command to a file named foo.txt, replacing the existing contents of the file. In other words, the contents of the file will be overwritten.
Appending the output or data to the file
The syntax is
command >> filename
For example the following will append data:
- 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 ➔
Verify it:
cat /tmp/data.txt
How to save the output of a command to a file in bash using tee command
The tee command read from standard input and write to standard output and files. The syntax is as follows for writing data into the file:
command | tee file.txt
Want to append data? Try
command | tee -a output.txt
Examples
Display output of the date command on screen and save to the file named /tmp/output.txt. If the output.txt already exists, it gets overwritten:
$ date | tee /tmp/output.txt
$ cat /tmp/output.txt
Same as above but append to the given files, do not overwrite file:
$ pwd | tee -a /tmp/test.txt
$ echo «Today is $(date)» | tee -a /tmp/test.txt
$ hostnamectl | tee -a /tmp/test.txt
$ cat /tmp/test.txt
The above commands will append the output to the end of the file, just like the shell >> operator as explained earlier.
I/O redirection summary for bash and POSIX shell
Shell operator | Description | Overwrite existing file? |
---|---|---|
command > output.txt | Save terminal output (standard output) to a file named output.txt | Yes |
command >> output.txt | Append terminal output (standard output) to a file named output.txt | No |
command | Takes standard input from output.txt file | N/A |
command 0 | Takes standard input from output.txt file | N/A |
command 1> output.txt | Puts standard output to output.txt file | Yes |
command 1>> output.txt | Appends standard output to output.txt | No |
command 2> output.txt | Puts standard error to output.txt | Yes |
command 2>> output.txt | Appends standard error to output.txt file | No |
command &> output.txt | Puts both standard error and output to output.txt | Yes |
command > output.txt 2>&1 | <POSIX> Puts both standard error and output to file named output.txt | Yes |
command &>> output.txt | Appends both standard error and output to file named output.txt | No |
command >> output.txt 2>&1 | <POSIX> Appends both standard error and output to file called output.txt | No |
command | tee output.txt | Puts standard output to output.txt while displaying output on screen | Yes |
command | tee -a output.txt | Appends standard output to output.txt while displaying output on screen | No |
command |& tee output.txt | Puts both standard output and error to output.txt while displaying output on terminal | Yes |
command 2>&1 | tee output.txt | <POSIX> Puts both standard output and error to file named output.txt while displaying output on terminal | Yes |
command |& tee -a output.txt | Append both standard output and error to file called output.txt while displaying output on terminal | No |
command 2>&1 | tee -a output.txt | <POSIX> Append both standard output and error to file named output.txt while displaying output on terminal | No |
Conclusion
You learned how to write the output to the file in Linux or Unix-like system when using bash or POSIX shell. We have:
- /dev/stdin (standard input) — File descriptor 0 is duplicated.
- /dev/stdout (standard output) — File descriptor 1 is duplicated.
- /dev/stderr (standard error) — File descriptor 2 is duplicated.
See I/O redirection documentation for more information. We can read bash man page as follows using the man command:
man bash
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Command output to text file linux
В данной статье пойдет речь о том, как перенаправить вывод любой команды терминала (консоли) 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 и нажимаем «Печать».
Источник