IO重定向

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
  1. 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&-
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值