How to redirect stdin/stdout/stderr in Bash

(redirect stdout to file)
$ cmd > file

(same but append to file)
$ cmd >> file

(redirect  stderr to file)
$ cmd 2> file

(redirect stdout and stderr to file)
$ cmd &> file
or 
$ cmd > file 2>&1
or
$ cmd >& file

(same but to null)
$ cmd &> /dev/null

(redirect stderr to stdout)
$ cmd 2>&1

(redirect stdout to stderr)
$ cmd 1>&2

(redirect stdin from file)
$ cmd < file

(redirect a bunch of lines to the stdin; here-document)
$ cmd << EOL
line1
line2
EOL

(redirect single line of text to stdin of cmd; here-string)
$ cmd <<< "string" 
or
$ echo "string" | cmd

(redirect stdout of cmd1 to stdin of cmd2)
$ cmd1 | cmd2

(redirect stdout and stderr of cmd1 to stdin of cmd2)
$ cmd1 |& cmd2 
or
$ cmd1 |& cmd2 

(redirect stdout to file and screen)
$ cmd | tee file

(swap stdout and stderr of cmd)
$ cmd 3>&1 1>&2 2>&3 3>&-

(redirect stdout from multiple commands to a file)
$ (cmd1; cmd2) > file

(redirect stdout to one process and stderr to another process)
$ cmd > >(stdout_cmd) 2> >(stderr_cmd)

(redirect stderr of all commands to a file forever)
$ exec 2> file 

(open a file for reading using a custom file descriptor)
$ exec 3< file

(open a file for reading using a custom file descriptor)
$ exec 3> file

(open a file for reading and writing using a custom file descriptor)
$ exec 3<> file

(close a file descriptor)
$ exec 3>&-

(copy file descriptor 3 to 4)
$ exec 4>&3

(same as above but close 3)
$ exec 4>&3-

(write to a custom file descriptor)
$ echo "foo" >&3

(read from a custom file descriptor)
$ cat <&3

see BASH Programming – Introduction HOW-TO
see Bash Redirections Cheat Sheet
see Bash One-Liners Explained, Part III: All about redirections
see Redirection tutorial

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s