Linux send 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

Источник

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:

  1. /dev/stdin (standard input) — File descriptor 0 is duplicated.
  2. /dev/stdout (standard output) — File descriptor 1 is duplicated.
  3. /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

Источник

Explained: Input, Output and Error Redirection in Linux

If you are familiar with the basic Linux commands, you should also learn the concept of input output redirection.

You already know how a Linux command functions. It takes an input and gives you an output. There are a few players in the scene here. Let me tell you about them.

Stdin, stdout and stderr

When you run a Linux command, there are three data stream that play a part in it:

  • Standard input (stdin) is the source of input data. By default, stdin is any text entered from the keyboard. It’s stream ID is 0.
  • Standard output (stdout) is the outcome of command. By default, it is displayed on the screen. It’s stream ID is 1.
  • Standard error (stderr) is the error message (if any) produced by the commands. By default, stderr is also displayed on the screen. It’s stream ID is 2.

These streams contain the data in plain text in what’s called buffer memory.

Think of it as water stream. You need a source for water, a tap for example. You connect a pipe to it and you can either store it in a bucket (file) or water the plants (print it). You can also connect it to another tap, if needed. Basically, you are redirecting the water.

Linux also has this concept of redirection, where you can redirect the stdin, stdout and stderr from its usual destination to another file or command (or even peripheral devices like printers).

Let me show how redirection works and how you can use it.

The output redirection

The first and simplest form of redirection is output redirection also called stdout redirection.

You already know that by default, the output of a command is displayed on the screen. For example, I use the ls command to list all the files and this is the output I get:

With output redirection, you can redirect the output to a file. If this output files doesn’t exist, the shell will create it.

For example, let me save the output of the ls command to a file named output.txt:

The output file is created beforehand

What do you think the content of this output file should be? Let me use the cat command to show you a surprise:

Did you notice that the inclusion of output.txt there? I deliberately chose this example to show you this.

The output file to which the stdout is redirected is created before the intended command is run. Why? Because it needs to have the output destination ready to which the output will be sent.

Append instead of clobber

One often ignored problem is that if you redirect to a file that already exists, the shell will erase (clobber) the file first. This means the existing content of the output file will be removed and replaced by the output of the command.

You can append, instead of overwriting it, using the >> redirection syntax.

Tip: You can forbid clobbering in current shell session using: set -C

Why would you redirect stdout? You can store the output for future reference and analyze it later. It is specially helpful when the command output is way too big and it takes up all of your screen. It’s like collecting logs.

Pipe redirection

Before you see the stdin redirection, you should learn about pipe redirection. This is more common and probably you’ll be using it a lot.

With pipe redirection, you send the standard output of a command to standard input of another command.

Let me show you a practical example. Say, you want to count the number of visible files in the current directory. You can use ls -1 (it’s numeral one, not letter L) to display the files in the current directory:

You probably already know that wc command is used for counting number of lines in a file. If you combine both of these commands with pipe, here’s what you get:

With pipe, both commands share the same memory buffer. The output of the first command is stored in the buffer and the same buffer is then used as input for the next command.

You’ll see the result of the last command in the pipeline. That’s obvious because the stdout of earlier command(s) is fed to the next command(s) instead of going to the screen.

Pipe redirection or piping is not limited to connecting just two commands. You may connect more commands as long as the output of one command can be used as the input of the next command.

Remember the stdout/stdin is a chunk of data, not filenames

Some new Linux users get confused while using the redirection. If a command returns a bunch of filenames as output, you cannot use those filenames as argument.

For example, if you use the find command to find all the files ending with .txt, you cannot pass it through pipe to move the found files to a new directory, not directly like this:

This is why you’ll often see find command used in conjugation with exec or xargs command. These special commands ‘convert the text with bunch of filenames into filename’ that can be passed as argument.

The input redirection

You can use stdin redirection to pass the content of a text file to a command like this:

You won’t see stdin being used a lot. It’s because most Linux commands accept filenames as argument and thus the stdin redirection is often not required.

Take this for example:

The above command could have just been head filename.txt (without the or >> redirection symbol that you used for stdout redirection.

But how do you distinguish between the stdout and stderr when they are both output data stream? By their stream ID (also called file descriptor).

Data Stream Stream ID
stdin 0
stdout 1
stderr 2
-t, –list
-u, –update
-x, –extract, –get
-j, –bzip2
-z, –gzip, –gunzip, –ungzip

By default when you use the output redirection symbol >, it actually means 1>. In words, you are saying that data stream with ID 1 is being outputted here.

When you have to redirect the stderr, you use its ID like 2> or 2>>. This signifies that the output redirection is for data stream stderr (ID 2).

Stderr redirection examples

Let me show it to you with some examples. Suppose you just want to save the error, you can use something like this:

That was simple. Let’s make it slightly more complicated (and useful):

In the above example, the ls command tries to display two files. For one file it gets success and for the other, it gets error. So what I did here is to redirect the stdout to ouput.txt (with >) and the stderr to the error.txt (with 2>).

You can also redirect both stdout and stderr to the same file. There are ways to do that.

In the below example, I first send the stderr (with 2>>) to combined.txt file in append mode. And then, the stdout (with >>) is sent to the same file in append mode.

Another way, and this is the preferred one, is to use something like 2>&1. Which can be roughly translated to “redirect stderr to the same address as stdout”.

Let’s take the previous example and this time use the 2>&1 to redirect both of the stdout and stderr to the same file.

Keep in mind that you cannot use 2>>&1 thinking of using it in append mode. 2>&1 goes in append mode already.

You may also use 2> first and then use 1>&2 to redirect stdout to same file as stderr. Basically, it is “>&” which redirects one out data stream to another.

Summary

  • There are three data streams. One input, stdin (0) and two output data streams stdout (1) and stderr (2).
  • Keyboard is the default stdin device and the screen is the default output device.
  • Output redirection is used with > or >> (for append mode).
  • Input redirection is used with or 2>>.
  • The stderr and stdout can be combined using 2>&1.

Since you are learning about redirection, you should also know about the tee command. This command enables you to display to standard output and save to file simultaneously.

I hope you liked this detailed guide on redirection in Linux. If you still have doubts or if you have suggestions to improve this article, please let me know in the comment section.

Источник

Читайте также:  Права администратора windows 10 что дают
Оцените статью