Ubuntu – How to redirect stderr to a file

command lineredirect

While using nohup to put a command to run in background some of content appear in terminal.

cp: error reading ‘/mnt/tt/file.txt’: Input/output error
cp: failed to extend ‘/mnt/tt/file.txt’: Input/output error

I want to save that content to a file.

Best Answer

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:

  1. Redirect stdout to one file and stderr to another file:

    command > out 2>error
    
  2. Redirect stdout to a file (>out), and then redirect stderr to stdout (2>&1):

    command >out 2>&1
    
  3. 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):

    command &> out
    

For more information on the various control and redirection operators, see here.