Introduction – You can easily redirect error messages in Unix and Linux when using KSH, SH, and BASH.
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.
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
command 1> file
ls 1> /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:
KSH redirect error messages to standard output (stdout)
The syntax is:
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
ls /nonexistanc 2>&-
command > /dev/null 2>&1
grep -R "something" /etc/ > /dev/null 2>&1
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: