redirection
show file descriptors of current bash session
lsof -ap $BASHPID -d 0-9
file descriptors
0 # stdin
1 # stdout
2 # stderr
3 to 9 # can be assigned freely
redirect stdin to file
command 0<file
command <file
redirect stdout to file
command 1>file
command >file
force redirect stdout to existing file (if noclobber is set)
command >|file
redirect stderr to file
command 2>file
redirect stderr to stdout
command 2>&1
redirect stdout to stderr
command 1>&2
redirect stdout and stderr to seperate files
command 1>file-stdout 2>file-stderr
redirect stdout and stderr to single file
command >file 2>&1
command &>file
redirect errors to stdout and stdout to file
command 2>&1 >file
redirect stderr permanently in scripts
exec 2>/dev/null
close/disable file descriptor n
command n>&-
open file descriptor n to read/write from/to file
exec n<>file
examples
redirect stdout/stderr from within script
LOG_FILE="/path/to/logfile"
exec 1> "$LOG_FILE"
exec 2>&1
redirect fd3 output to file
exec 3>file # open fd3 input
echo "foobar" >&3 # read from fd3
exec 3>&- # close fd3
redirect fd3 input to file
exec 3<file # open fd3 output
read foobar <&3 # write to fd3
exec 3>&- # close fd3
redirect stdin/stdout from/to fd3
exec 3<>file # open file and assign fd 3 to it
read -n 10 <&3 # read 10 characters from file
echo -n "x" >&3 # write new character to file
exec 3>&- # close fd
only print to stderr if explicitely wanted
exec 3>&2- # move stderr to fd3 and close fd2
ls -l /foobar # error not shown
ls -l /foobar 2>&3 # error shown
exec 2>&3- # restore stderr from sd3 and close fd3
ls -l /foobar # error shown
ls -l /foobar 2>&3 # invalid file descriptor
links
https://wiki.bash-hackers.org/howto/redirection_tutorial
https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Redirections
https://tldp.org/LDP/abs/html/io-redirection.html
last updated: Sat Aug 12 14:29:24 2023