The tee command takes the standard input and sends it to one or more files and the standard output. The tee command is derived from the pipe T-splitter. It simply breaks down a program’s output so that it can be shown and saved in a file. It performs both jobs simultaneously, copies the output to the given files or variables, and displays the output.
Syntax:
Options:
- -a: append (instead of overwriting the files, append them to the existing ones)
- -i: ignore interrupts (ignore the signals that interrupt)
Files: There are multiple files. The output data is written to each of them.
The default file descriptor for the process of writing error messages is stderr, often known as standard error. Standard errors can be forwarded to the command line in Bash. This article is about redirecting the output from stderr using the tee command in different scenarios.
Redirect stderr Using the tee Command
Standard errors are forwarded to the Command Line in Bash. Redirecting stderr might let you capture error messages in a distinct log file or eliminate the error messages completely. We will explain the procedure to redirect stderr using the tee command with the following examples.
Step 1: Create a Bash File
First, create a Bash file “linux.sh” using the following command:
Step 2: Write the Code
Now, write the following code in the file, or you can write something else according to your requirement:
echo hello
1>&2 echo world
Step 3: Check If the Bash File Is Working
Now, check whether the Bash file is working properly or whether the code written in it is correct by running the following command in the terminal:
The given outcome outputs the correct result, which proves that the code is working properly.
Run another command mentioned below to check the working code:
Now, run the following command to check the working of the code:
We got the expected output; it means the code is correct.
Step 4: Redirect the stderr to the tee command
The >(…) (process substitution) establishes a FIFO and makes it available to the tee for listening. Then, it employs > (file redirection) to send the command’s STDOUT to the FIFO that your first tee is monitoring.
The following command redirects stderr to the tee. It redirects the output to “/tmp/log”:
Now, output the file into which we redirected the output.
By default, tee prints to STDOUT. Print this to STDERR.
Conclusion
The tee command reads the data from an input file/files and writes the received output to many files. Redirecting errors to stderr can be done with the help of the tee command. There are many ways to redirect the output. But in this article, we described a procedure, with the help of an example, to redirect stderr to the tee using a Bash file and displayed the output on Ubuntu (Linux Operating System). You will find this article helpful in redirecting stderr using the tee command.