- 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
- 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 Save the Output of a Command to a File in Linux Terminal [Beginner’s Tip]
- Method 1: Use redirection to save command output to file in Linux
- Method 2: Use tee command to display the output and save it to a file as well
- Note: Avoid pipe pitfall while saving command output to file
- How to redirect stderr to a file [duplicate]
- 2 Answers 2
- Shell redirections
- Commands writing to stderr exclusively
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
Источник
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 Save the Output of a Command to a File in Linux Terminal [Beginner’s Tip]
Last updated April 17, 2021 By Abhishek Prakash 3 Comments
When you run a command or script in the Linux terminal, it prints the output on the screen for your immediate viewing.
There will be times when you need to save the output to a file for future references. Now, you can surely copy and paste in Linux terminal but there are better ways to save the output of a shell script or command in Linux command line. Let me show them to you.
Method 1: Use redirection to save command output to file in Linux
You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file.
- The > redirects the command output to a file replacing any existing content on the file.
- The >> redirects adds the command output at the end of the existing content (if any) of the file.
Use the STDOUT redirection operator > for redirecting the output to a file like this:
If the file.txt doesn’t exist, it will be created automatically. If you use the > redirect again with the same file, the file content is replaced by the new output.
The example below demonstrates it better. It first saves the output of ls -l command. And then later, it replaces the content of the file with the output of ls *.c command.
If you don’t want to lose the content of the existing file while saving the output of a script or command, use the redirection operation in append mode with >>.
This example demonstrates it better:
Even here if the file doesn’t exist, it is created automatically.
Bonus Tip: Save Linux command output as well as error to a file
If your Linux command returns an error, it doesn’t get saved in the file. You can save both the command output and command error in the same file using 2>&1 like this:
command > file.txt 2>&1
Basically, 0 stands for standard input, 1 for standard output and 2 for standard error. Here, you are redirecting (>) standard error (2) to same address (&) as standard output (1).
Method 2: Use tee command to display the output and save it to a file as well
By the way, did you notice that when you send the command output to a file, you cannot see it anymore on the display? The tee command in Linux solves this problem for you.
Like a tee pipe that sends water stream into two directions, the tee command send the output to the display as well as to a file (or as input to another command). You can use it like this:
Again, the file will be created automatically, if it doesn’t exist already.
You may also use the tee command in append mode with option -a in this manner:
Let me demonstrate it with some easy to follow examples:
I have used simple Linux commands in my examples. But rest assured, you can use these methods to save the output of bash scripts as well.
Note: Avoid pipe pitfall while saving command output to file
You probably are familiar with pipe redirection. You may use it to combine Linux commands but you cannot pipe the output to a file. It will result in error that filename command not found:
This is because pipe redirects the output of one command to input of another command. And in this case, you give it a file name while it was expecting a command.
If you are new to Linux command line, I hope this quick tutorial added to your Linux knowledge a bit. I/O redirection is an essential concept that one should be aware of.
As always, questions and suggestions are always welcome.
Like what you read? Please share it with others.
Источник
How to redirect stderr to a file [duplicate]
While using nohup to put a command to run in background some of content appear in terminal.
I want to save that content to a file.
2 Answers 2
There are two main output streams in Linux (and other OSs), standard output (stdout) and standard error (stderr). Error messages, like the ones you show, are printed to standard error. The classic redirection operator ( command > file ) only redirects standard output, so standard error is still shown on the terminal. To redirect stderr as well, you have a few choices:
Redirect stdout to one file and stderr to another file:
Redirect stdout to a file ( >out ), and then redirect stderr to stdout ( 2>&1 ):
Redirect both to a file (this isn’t supported by all shells, bash and zsh support it, for example, but sh and ksh do not):
For more information on the various control and redirection operators, see here.
First thing to note is that there’s couple of ways depending on your purpose and shell, therefore this requires slight understanding of multiple aspects. Additionally, certain commands such as time and strace write output to stderr by default, and may or may not provide a method of redirection specific to that command
Basic theory behind redirection is that a process spawned by shell (assuming it is an external command and not shell built-in) is created via fork() and execve() syscalls, and before that happens another syscall dup2() performs necessary redirects before execve() happens. In that sense, redirections are inherited from the parent shell. The m&>n and m>n.txt inform the shell on how to perform open() and dup2() syscall (see also How input redirection works, What is the difference between redirection and pipe, and What does & exactly mean in output redirection )
Shell redirections
Most typical, is via 2> in Bourne-like shells, such as dash (which is symlinked to /bin/sh ) and bash ; first is the default and POSIX-compliant shell and the other is what most users use for interactive session. They differ in syntax and features, but luckily for us error stream redirection works the same (except the &> non standard one). In case of csh and its derivatives, the stderr redirection doesn’t quite work there.
Let’s come back to 2> part. Two key things to notice: > means redirection operator, where we open a file and 2 integer stands for stderr file descriptor; in fact this is exactly how POSIX standard for shell language defines redirection in section 2.7:
For simple > redirection, the 1 integer is implied for stdout , i.e. echo Hello World > /dev/null is just the same as echo Hello World 1>/dev/null . Note, that the integer or redirection operator cannot be quoted, otherwise shell doesn’t recognize them as such, and instead treats as literal string of text. As for spacing, it’s important that integer is right next to redirection operator, but file can either be next to redirection operator or not, i.e. command 2>/dev/null and command 2> /dev/null will work just fine.
The somewhat simplified syntax for typical command in shell would be
The trick here is that redirection can appear anywhere. That is both 2> command [arg1] and command 2> [arg1] are valid. Note that for bash shell, there there exists &> way to redirect both stdout and stderr streams at the same time, but again — it’s bash specific and if you’re striving for portability of scripts, it may not work. See also Ubuntu Wiki and What is the difference between &> and 2>&1.
Note: The > redirection operator truncates a file and overwrites it, if the file exists. The 2>> may be used for appending stderr to file.
If you may notice, > is meant for one single command. For scripts, we can redirect stderr stream of the whole script from outside as in myscript.sh 2> /dev/null or we can make use of exec built-in. The exec built-in has the power to rewire the stream for the whole shell session, so to speak, whether interactively or via script. Something like
In this example, the log file should show stat: cannot stat ‘/etc/non_existing_file’: No such file or directory .
Yet another way is via functions. As kopciuszek noted in his answer, we can write function declaration with already attached redirection, that is
Commands writing to stderr exclusively
Commands such as time and strace write their output to stderr by default. In case of time command, the only viable alternative is to redirect output of whole command , that is
alternatively, synchronous list or subshell could be redirected if you want to separate the output ( as shown in related post ):
Other commands, such as strace or dialog provide means to redirect stderr. strace has -o option which allows specifying filename where output should be written. There is also an option for writing a textfile for each subprocess that strace sees. The dialog command writes the text user interface to stdout but output to stderr, so in order to save its output to variable ( because var=$(. ) and pipelines only receives stderr ) we need to swap the file descriptors
but additionally, there is —output-fd flag, which we also can utilize. There’s also the method of named pipes. I recommend reading the linked post about the dialog command for thorough description of what’s happening.
Источник