重定向的分类
名称 |
文件描述符 |
作用 |
标准输入(stdin) |
0 |
通常是键盘输入(其他输入命令的终端设备) |
标准输出(stdout) |
1 |
默认输出到屏幕 |
错误输出(stderr) |
2 |
默认输出到屏幕 |
文件名(filename) |
3+ |
|
进程描述符:一个进程或者终端在启动时,都会开启文件描述符。
[root@localhost ~]# ll /dev/st*
lrwxrwxrwx. 1 root root 15 Nov 28 18:49 /dev/stderr -> /proc/self/fd/2 #错误输出 2> 2>> 不能省略
lrwxrwxrwx. 1 root root 15 Nov 28 18:49 /dev/stdin -> /proc/self/fd/0 #标准输入 < << 0 可以省略
lrwxrwxrwx. 1 root root 15 Nov 28 18:49 /dev/stdout -> /proc/self/fd/1 #标准输出 > >> 1 可以省略
[root@localhost ~]# ll /proc/121169/fd/
总用量 0
lrwx------ 1 root root 64 4月 7 11:28 0 -> /dev/pts/3
lrwx------ 1 root root 64 4月 7 11:28 1 -> /dev/pts/3
lrwx------ 1 root root 64 4月 7 11:27 2 -> /dev/pts/3
lr-x------ 1 root root 64 4月 7 11:28 3 -> /var/log/messages
类型 |
符号 |
用途 |
备注 |
标准覆盖输出重定向 |
1> |
将命令执行的正确结果默认输出的位置,修改为指定的文件或者终端(覆盖原有内容) |
通常'>'即可,1可以不写,默认就是1 |
标准追加输出重定向 |
>> |
将命令执行的正确结果,输出到指定文件的末尾(不覆盖原有内容) |
|
错误覆盖输出重定向 |
2> |
将命令执行的错误结果默认输出的位置,修改为指定的文件或者终端(覆盖原有内容) |
|
错误追加输出重定向 |
2>> |
将命令执行的错误结果,输出到指定文件的末尾(不覆盖原有内容) |
|
标准输入重定向 |
0< |
将命令中接收输入内容由默认的键盘,改为命令或者文件 |
通常'<'即可0可以写也可以不写,默认0 |
标准输入追加重定向 |
0<< |
将命令中接收输入内容由默认的键盘,改为命令或者文件 |
|
输出重定向
将标准输出重定向到文件
# 将标准输出重定向到终端
[root@wqh06 pts]# echo "w shi da shui bi" > /dev/pts/1
# 标准覆盖输出重定向到文件
[root@localhost ~]# echo wqh>/tmp/1.txt
[root@localhost ~]# cat /tmp/1.txt
wqh
[root@localhost ~]# echo 321>/tmp/2.txt
[root@localhost ~]# cat /tmp/2.txt
[root@localhost ~]# echo wqh1>/tmp/3.txt
[root@localhost ~]# cat /tmp/3.txt
wqh1
将标准输出追加重定向到文件
# 标准追加输出重定向
[root@localhost ~]# echo 456 >> /var/log/messages
[root@localhost ~]# echo 123 >> /var/log/messages
将错误输出重定向到文件
# 错误输出重定向
[cdx@localhost ~]$ find /etc/ -type d 2> finderror.txt # 普通用户权限有时受限
[cdx@localhost ~]$ find /etc/ -type d > findright.txt 2> finderror.txt # 正确结果和错误结果分开保存
将标准输出和错误输出都重定向到文件
# 将标准输出和错误输出都输出到相同的文件中
[cdx@localhost ~]$ find /etc/ -type d > /tmp/100.txt 2>&1 # 错误输出需要由 1 输出到文件中
[cdx@localhost ~]$ find /etc/ -type d &> /tmp/101.txt # 错误输出和标准输出 同时输出到文件中
# 将错误输出,重定向到黑洞
[root@localhost ~]# ls / /ooo 2> /dev/null
# 脚本中使用重定向
#!/bin/bash
. /etc/init.d/functions
read -p "请输入要检测的IP:" IP
ping -c1 -W1 $IP &> /dev/null
if [ $? -eq 0 ];then
action "$IP" /bin/true >> /tmp/IP_OK.txt
else
action "$IP" /bin/false >> /tmp/IP_FAILD.txt
fi
输入重定向
[root@localhost ~]# mail -s "$(date +%F-%T)_test" [email protected] < /etc/passwd