Blog

03/06/2019

Linux Redirect Error Output To File



I am a new Ubuntu Linux and bash shell user. I also know how to redirect output from display/screen to a file using the following syntax:

cmd > file
ls > file

However, some time errors are displayed on screen. How do I store and redirect output from the computer screen to a file on a Linux or Unix-like systems?

[donotprint][/donotprint] Bash / ksh and other modern shell on Linux has three file descriptors:

  1. stdin (0)
  2. stdout (1)
  3. stderr (2)

Syntax To redirect all output to file

The syntax is as follows to redirect output (stdout) as follows:

command-name >  output.txt
command-name >  stdout.txt

Syntax To redirect all error to file

The syntax is as follows to redirect errors (stderr) as follows:

command-name 2> errors.txt
command-name 2> stderr.txt

Syntax to redirect both output (stdout) and errors (stderr) to different files

The syntax:

command1 > out.txt 2> err.txt
command2 -f -z -y > out.txt 2> err.txt

Syntax to redirect both output (stdout) and errors (stderr) to same file

The syntax is:

command1 > everything.txt 2>&1
command1 -arg > everything.txt 2>&1

Syntax to redirect errors (stderr) to null or zero devices

Data written to a null or zero special file is discarded by your system. This is useful to silence out errors (also know as ‘error spam’):

command1 2> /dev/null
command1 2> /dev/zero
command2 -arg 2> /dev/null
command2 -arg 2> /dev/zero

Tip: Use tee command to redirect to both a file and the screen same time

The syntax is:

command1 |& tee log.txt
## or ##
command1 -arg |& tee log.txt
## or ##
command1 2>&1 | tee log.txt

Another usage:

#!/bin/bash
# My script to do blah ...
foo(){
 :
} 2>&1 | tee foo.log

OR

#!/bin/bash
# My script to do blah ...
{
   command1
   command2
} 2>&1 | tee script.log

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...