Differences between revisions 3 and 10 (spanning 7 versions)
Revision 3 as of 2008-11-22 21:20:11
Size: 1079
Editor: GreyCat
Comment: first-line
Revision 10 as of 2014-04-22 01:27:12
Size: 1458
Editor: GreyCat
Comment: fix dodgy example; refer to FAQ 106
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
Redirecting the standard output of a single command is as easy as Redirecting the standard output of a single command is as easy as:
Line 19: Line 19:
In a loop or other larger code structure: or, a fancier way:
Line 21: Line 21:
    for i in $list; do     # Bash only. Equivalent to date > file 2>&1 but non-portable.
    date &> file
}}}

Redirecting an entire loop:
{{{
    for i in "${list[@]}"; do
Line 35: Line 41:
Otherwise command grouping helps: (See [[BashFAQ/106|FAQ 106]] for more complex script logging techniques.)

Otherwise, command grouping helps:
Line 40: Line 48:
        # some other command         # some other commands
Line 46: Line 54:

[[http://wiki.bash-hackers.org/syntax/redirection|More discussion]]

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

----
CategoryShell

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

or, a fancier way:

    # Bash only.  Equivalent to date > file 2>&1 but non-portable.
    date &> file

Redirecting an entire loop:

    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"

(See FAQ 106 for more complex script logging techniques.)

Otherwise, command grouping helps:

    {
        date
        # some other commands
        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


CategoryShell

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