I/O Redirection
: > filename # The > truncates file "filename" to zero length
# If file not present, creates zero-length file (same effect as 'touch').
# The : serves as a dummy placeholder, producing no output.
> filename # Same result as ": >", above, but this does not work with some shells
M>N # "M" is a file descriptor, which defaults to 1, if not explicitly set.
# "N" is a filename
# File descriptor "M" is redirect to file "N"
M>&N # "M" is a file descriptor, which defaults to 1, if not set.
# "N" is another file descriptor
[j]<>filename # Open file "filename" for reading and writing, and assign file descriptor "j" to it.
# If "filename" does not exist, create it.
# If file descriptor "j" is not specified, default to fd 0, stdin.
echo "1234567890" > File
exec 3<> File
read -n 4 <&3
echo -n . >&3 # Write a decimal point there
exec 3>&- # Close fd 3
cat File # 1234.67890
Closing File Descriptors
n<&- # Close input file descriptor n.
0<&-, <&- # Close stdin.
n>&- # Close output file descriptor n.
1>&-, >&- # Close stdout.
exec <filename # Redirect stdin to a file
exec >filename # Redirect stdout to a designed file
exec N >filename # affects the entire script or current shell. Redirection in the PID of the script or shell from that point on has changed
N >filename # affects only the newly-forked process, not the entire script or shell
exec 6>&1 # Link file descriptor #6 with stdout
# Saves stdout
exec 1>&6 6>&- # Restore stdout and close file descriptor #6
----------------------------------------------
exec 4<&0 # backup stdin
exec < $1
exec 7>&1 # backup stdout
exec > $2
cat - | tr a-z A-Z
exec 1>&7 7>&- # restore stdout
exec 0<&4 4<&- # restore stdin
# obtain the number of a file
wc names.data | awk '{print $1}'
wc -l names.data | awk '{print $1}'
wc -l < names.data # Very clever
# Root UID 0
users with $UID 0 have root privileges
- IO redirect
# ls -l /dev/std*
/dev/stderr -> /proc/self/fd/2
/dev/stdin -> /proc/self/fd/0
/dev/stdout -> /proc/self/fd/1
exec fd > file,fd,dev
exec fd < file,fd,dev
# 备份stdout
exec 6 > &1
# stdout重定向到文件
exec 1 > stdout.txt
# 执行命令,但屏幕不再打印任何东西
ls -l
# 恢复stdout
exec 1 > &6
# 关闭fd6
exec 6 > &-
---------------------------------
# 脚本支持pipe
if [ $# -ne 0 ]; then
exec 0<$1
fi
while read line
do
echo $line
done <&0
exec 0&-