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

last updated in Categories , ,

I am working with KSH script on Unix operating system. How do I redirect error messages in Unix when using KSH? How can I redirect stdout and stderr with KSH on Linux or Unix-like systems?

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 on Linux or Unix

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

Posted by: Vivek Gite

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.

Start the discussion at www.nixcraft.com

Historical Comment Archive

3 comment

  1. Say you wanna send an error message to stderr(2) instead of stdout(1) from ksh:

    echo "Error: $0 shell script failed" >&2

    Still, have a question? Get help on our forum!