Differences between revisions 4 and 5
Revision 4 as of 2009-05-27 01:51:47
Size: 1260
Editor: localhost
Comment: [igli] TheBonsai's site is working again
Revision 5 as of 2009-05-27 01:53:52
Size: 1262
Editor: localhost
Comment: [igli] oops; links were round wrong way
Deletions are marked like this. Additions are marked like this.
Line 47: Line 47:
[[More discussion|http://bash-hackers.org/wiki/doku.php/syntax/redirection]]
[[In-depth: Illustrated Tutorial|http://bash-hackers.org/wiki/doku.php/howto/redirection_tutorial]]
[[http://bash-hackers.org/wiki/doku.php/syntax/redirection|More discussion]]

[[http://bash-hackers.org/wiki/doku.php/howto/redirection_tutorial|In-depth: Illustrated Tutorial]]

How can I redirect the output of multiple commands at once?

Redirecting the standard output of a single command is as easy as

    date > file

To redirect standard error:

    date 2> file

To redirect both:

    date > file 2>&1

In a loop or other larger code structure:

    for i in $list; do
        echo "Now processing $i"
        # more stuff here...
    done > file 2>&1

However, this can become tedious if the output of many programs should be redirected. If all output of a script should go into a file (e.g. a log file), the exec command can be used:

    # redirect both standard output and standard error to "log.txt"
    exec > log.txt 2>&1
    # all output including stderr now goes into "log.txt"

Otherwise command grouping helps:

    {
        date
        # some other command
        echo done
    } > messages.log 2>&1

In this example, the output of all commands within the curly braces is redirected to the file messages.log.

More discussion

In-depth: Illustrated Tutorial

BashFAQ/014 (last edited 2015-03-05 00:29:41 by izabera)