Linux error out to file

How to redirect standard (stderr) error in bash

I am trying to redirect bash message into file named output.log. But, it is not getting redirected. How do I redirect both standard output and standard error in bash shell? In Linux, how do I redirect error messages?

Standard error (also known as stderr) is the default error output device. Use stderr to write all system error messages. The number (FD – File Descriptors) two (2) denotes the stderr. The default stderr is the screen or monitor. Standard output (also known as stdout) is used by a command to writes (display) its output. The default stdout is the screen. It is denoted by one number (1).

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux, macOS or Unix-like OS with Bash
Est. reading time 3 minutes

2> is input redirection symbol and syntax is:

  1. To redirect stderr (standard error) to a file:
    command 2> errors.txt
  2. Let us redirect both stderr and stdout (standard output):
    command &> output.txt
  3. Finally, we can redirect stdout to a file named myoutput.txt, and then redirect stderr to stdout using 2>&1 (errors.txt):
    command > out 2>errors.txt

Make sure you use >> for appending data/log if the file already has data. For instance:

How to redirect standard error in bash

Run find command and save all error messages to find.error.txt file:
find / -name «*.conf» 2> find.error.txt
You can view find.error.txt with the cat command:
cat find.error.txt
Sample outputs:

You need to use “2>” when you want to redirect stderr to a file. You can redirect stdout to file named results.txt and stderr to file named errors.txt:
find / -name «*.conf» >results.txt 2>error.txt
Verify results with the cat command:
cat results.txt
cat error.txt
This is useful in shell scripts or any other purpose.

How to redirect standard error and standard output in bash

You can send both stdout and stderr to a file named output.txt
command &>output.xt
find / -name «*.pl» &>filelist.txt
Please note that both errors and actual output of the find command stored into a file:
cat filelist.txt
Sample outputs:

  • 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

Summary

Command Description/Purpose
command 2>filename Redirect stderr to filename
command >output.txt 2>error.log
cat output.txt error.txt
Redirect stderr to file named error.log and stdout to file named output.txt
command &> filename Redirect stderr and stdout to filename
command 2>&- Just suppress error messages. No file created. No error message displayed on screen
command 1>&2
Sample code:
Redirect error messages to standard output. Useful in shell script when you need to forcefully display error messages on screen

For more info see bash man page online or read it at the cli by using the man command:
man bash

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

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

The numbers are actually file descriptors.

  • 0 = stdin
  • 1 = stdout
  • 2 = stderr

yes they are. thanks for comment.

Hi, Vitek!
It seems there is a mistake in your article, specifically the fifth example in your conclusive summarizing table is wrong in my opinion. I had tried to post you a reply, but it turned to be too long and the site refused to accept it. So I designed it as a text file, zipped it as a tar archive and uploaded to a filehosting. Please take some time, download it and read my message. Perhaps I’m wrong, still it seems to me, I’ve found a flaw in your article.

I can’t find your zip file. However, I updated my 5th example.

I have read your article “How to Redirect Standard Error in Bash” on the link https://www.cyberciti.biz/faq/how-to-redirect-standard-error-in-bash/ dedicated to the redirection of standard input/output streams,
however I couldn’t understand the meaning of your last instruction in the article and the example below.

Redirect error messages to standard output. Useful in shell script when you need
to forcefully display error messages on screen

The 2>&1 command really redirects stderr to stdout, but it seems in most cases this construction won’t work as it was thought out. In your example you redirect the stderr of echo, but echo always sends its output to stdout, not stderr, thus this redirection will take no effect and the “File not found” message will be sent to stdout any case. On the other hand, if the standard output has been already redirected to some file, say “msg.txt”, the 2>&1 construction will redirect stderr to the same “msg.txt” file and put all your error messages together with normal output.

I think what you really meant was the construction 1>&2 which redirects stdout to stderr. Then the standard output of the script may be redirected to some file or a pipe, still the error messages will appear on the screen or a terminal. So your instruction possibly should be rewritten in some way like:

Redirect error messages from standard output to standard error stream. Useful in a shell script when you need to forcefully display error messages on the screen, no matter was the script’s output redirected to a file or a pipe or not. The construction is useful with commands like echo or printf, which always print the text to the standard output, and makes them print error messages to the standard error stream.

Per contra, the 2>&1 operator is useful when you want your script’s or program’s error messages to get to the same stream as normal output. In that case it must be preceded by the stdout redirection, otherwise it won’t work. For example,

As far as I know, it’s a common practice to use in modern shells a brief simplified notation:

instead of the old traditional

but the meaning of both notations (modern simplified and the old verbose one)
is quite the same. Please look through my post and comment it. I’m not a shell programming expert, so I may be wrong, but it seems I’ve found a small mistake in your article.

Thanks. I fixed the page. I appreciate your feedback.

Источник

KSH redirect stdout and stderr to a file on Linux or Unix

What is stdout?

The stdout (stdout) is nothing but standard output used by a command to write its output on the screen. It is denoted by one (1) number.

What is stderr?

The standard error (stderr) is the default error output device, which is used to write all system error messages. It is denoted by two (2) number.

  • 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

KSH redirect stdout and stderr

Let us see some common examples for Linux and Unix-based systems.

How to redirect stdout to a file

The standard output (stdout) redirect to file is as follows:
command > file
ls > /tmp/list.txt
cat /tmp/list.txt
OR
command 1> file
ls 1> /tmp/list.txt
cat /tmp/list.txt
The ls > /tmp/list.txt is just a shortcut for ls 1> /tmp/list.txt .

KSH redirect stderr to a file

To redirect standard error messages on Linux to a file named errors.txt, enter:
command-name 2> errors.txt
Make sure you replace command-name with the Unix command you want to run, for example:
find / -name «resolv.conf» * 2> /tmp/errors.txt
Use cat command to see errors stored in errors.txt file:
cat /tmp/errors.txt

KSH redirect error messages to standard output (stdout)

The syntax is:
command 2>&1
gunzip * 2>&1

How to redirect both standard error and standard out to a file

Try the following syntax:
command > file 2>&1
find / -name «nginx.conf» -print > command.out 2>&1

How to hide or suppress error messages with ksh

Simply use:
command 2>&-
ls /nonexistanc
ls /nonexistanc 2>&-

How to redirect both stdout and stderr to /dev/null

Try:
command > /dev/null 2>&1
grep -R «something» /etc/ > /dev/null 2>&1
echo $?

Conclusion

KSH redirection refers to changing the shell’s normal method of handling stdout , stdin, and stderr for Unix commands. KSH uses the following symbols for redirection purpose:

  • > : redirect stdout (overwrite)
  • >> : redirect stdout (append)
  • : redirect stdin
  • 2> : redirect stderr
  • 2>&1 : redirect stderr to stdout

For more information read ksh man page by typing the following man command:
man ksh

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

Источник

BASH Shell Redirect stderr To stdout ( redirect stderr to a File )

Table of contents

Understanding I/O streams numbers

The Unix / Linux standard I/O streams with numbers:

Tutorial requirements
Requirements Unix or Linux with bash
Root privileges No
Difficulty Easy
Est. reading time 6 mintues
Handle Name Description
0 stdin Standard input
1 stdout Standard output
2 stderr Standard error

Redirecting output

Redirecting the standard error stream to a file

The following will redirect program error message to a file called error.log:
$ program-name 2> error.log
$ command1 2> error.log
For example, use the grep command for recursive search in the $HOME directory and redirect all errors (stderr) to a file name grep-errors.txt as follows:
$ grep -R ‘MASTER’ $HOME 2> /tmp/grep-errors.txt
$ cat /tmp/grep-errors.txt
Sample outputs:

Redirecting the standard error (stderr) and stdout to file

Use the following syntax:
$ command-name &>file
We can als use the following syntax:
$ command > file-name 2>&1
We can write both stderr and stdout to two different files too. Let us try out our previous grep command example:
$ grep -R ‘MASTER’ $HOME 2> /tmp/grep-errors.txt 1> /tmp/grep-outputs.txt
$ cat /tmp/grep-outputs.txt

Redirecting stderr to stdout to a file or another command

Here is another useful example where both stderr and stdout sent to the more command instead of a file:
# find /usr/home -name .profile 2>&1 | more

Redirect stderr to stdout

Use the command as follows:
$ command-name 2>&1
$ command-name > file.txt 2>&1
## bash only ##
$ command2 &> filename
$ sudo find / -type f -iname «.env» &> /tmp/search.txt
Redirection takes from left to right. Hence, order matters. For example:
command-name 2>&1 > file.txt ## wrong ##
command-name > file.txt 2>&1 ## correct ##

How to redirect stderr to stdout in Bash script

A sample shell script used to update VM when created in the AWS/Linode server:

  • 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

Our last example uses the exec command and FDs along with trap and custom bash functions:

Want both stderr and stdout to the terminal and a log file too?

Try the tee command as follows:
command1 2>&1 | tee filename
Here is how to use it insider shell script too:

Conclusion

In this quick tutorial, you learned about three file descriptors, stdin, stdout, and stderr. We can use these Bash descriptors to redirect stdout/stderr to a file or vice versa. See bash man page here:

Operator Description Examples
command>filename Redirect stdout to file “filename.” date > output.txt
command>>filename Redirect and append stdout to file “filename.” ls -l >> dirs.txt
command 2>filename Redirect stderr to file “filename.” du -ch /snaps/ 2> space.txt
command 2>>filename Redirect and append stderr to file “filename.” awk ‘< print $4>‘ input.txt 2>> data.txt
command &>filename
command >filename 2>&1
Redirect both stdout and stderr to file “filename.” grep -R foo /etc/ &>out.txt
command &>>filename
command >>filename 2>&1
Redirect both stdout and stderr append to file “filename.” whois domain &>>log.txt

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

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

What this mean?
$ command > file-name 2>&1

This means redirect stdout to file-name, with that in mind redirect stderr t stdout.
This will lead to both stderr and stdout go to file-name.

Sayed: that line means execute the command while redirecting both stdout and stderr to a file given by file-name.

A slightly more correct is:
The output of the ‘command’ is redirected to a ‘file-name’ and the error chanel (that is the ‘2’ is redirected to a pointer (?) of the output (‘&1’).
So stderr goes to the stdout and that goes to the file.

Actually it means “first redirect STDERR to STDOUT, so any errors printed out on STDERR should go to STDOUT. Then, execute ‘command’ and redirect its STDOUT to ‘file-name’” – keeping in mind that at this point STDOUT will also contain whatever is written to STDERR because of the earlier redirection.

Incorrect.
There are two incorrect concepts in your answer.

First is: the redirection happens from left to right. This means that the STDOUT is redirected first.
(When you have > without a stream number, it actually have an implicit 1)
And only after STDERR is redirected to “the same place STDOUT is pointing”, meaning, ‘file-name’

Second wrong concept with your answer is: There are no connection between the descriptors. Changing STDOUT after STDERR had been redirected to STDOUT won’t change STDERR.
It will make STDERR point to STDOUT and then change STDOUT to something else (without touching STDERR)
Here is a more detailed tutorial covering both those misconceptions
http://wiki.bash-hackers.org/howto/redirection_tutorial

I like the &>file one. but not for every stiuation.

In pre-bash4 days you HAD to do it this way:

cat file > file.txt 2>&1

now with bash 4 and greater versions… you can still do it the old way …but …

cat file &> file.txt

The above is bash4+ … some OLD distros may use prebash4 but I think they are alllong gone by now. Just something to keep in mind.

I really love: “ command2>&1 | tee logfile.txt

because tee log’s everything and prints to stdout . So you stil get to see everything! You can even combine sudo to downgrade to a log user account and add date’s subject and store it in a default log directory 🙂

Hi! good explanation, I’d like to make a function on C that redirects STDIN and SDTOUT to an script, how can I do that, I mean, the exist a library’s on C to put terminal sintaxis on C?, how would you start to do it? I’m very lost with this. Thankyou!

Источник

Читайте также:  Менеджер apple для windows
Оцените статью