Linux中数据流重定向

Linux下将本来应该在屏幕输出的内容保存在其他的地方,如保存在硬盘中,这就是数据流重定向。

正确输出错误输出

执行一个命令正确后返回的即为标准正确输出,错误则为标准错误输出。

[root@node02 /etc/yum.repos.d]# ll /hhh
# 错误输出,因为没有这个文件夹 ls: cannot access /hhh: No such file or directory [root@node02 /etc/yum.repos.d]# ll /root
# 以下为标准正确输出 total 48 -rw-------. 1 root root 1260 Oct 11 17:47 anaconda-ks.cfg -rw-r--r--. 1 root root 27964 Oct 11 17:47 install.log -rw-r--r--. 1 root root 8262 Oct 11 17:46 install.log.syslog -rw-r--r--. 1 root root 0 Oct 14 19:14 source

数据重导向

将正确输出和错误输出保存到文件为输出,将用户输入信息保存到文件为标准输入。

(1)标准输出,对应编号1,>为覆盖写,>>为追加写

# 同时打开两个文件夹,一个存在一个不存在,正确内容输出到文件,使用追加的方式
[root@node01 /home/yangchaolin]# ll decompress/ hehe/ 1>>stdout.txt
# 错误内容打印出来 ls: cannot access hehe/: No such file or directory [root@node01 /home/yangchaolin]# ll total 92 drwxr-xr-x. 2 root root 4096 Oct 20 09:53 decompress-rw-r--r--. 1 root root 72 Oct 20 10:39 stdout.txt
# 查看文件,内容为标准输出内容 [root@node01 /home/yangchaolin]# cat stdout.txt decompress/: total 20 -rw-------. 1 root root 18311 Oct 20 09:47 secure

(2)错误输出,对应编号2,>为覆盖写,>>为追加写

# 继续在上一次基础上,使用错误输出重定向,追加的方式
[root@node01 /home/yangchaolin]# ll decompress/ hehe/ 2>>stdout.txt
# 正确内容打印出来 decompress/: total 20 -rw-------. 1 root root 18311 Oct 20 09:47 secure
# 查看 [root@node01 /home/yangchaolin]# cat stdout.txt decompress/: total 20 -rw-------. 1 root root 18311 Oct 20 09:47 secure
# 错误内容被追加上去 ls: cannot access hehe/: No such file or directory

当然,也可以将正确内容和错误内容都输出,下面使用覆盖写的方式。

# 正确错误都重导向,使用2>&1
[root@node01 /home/yangchaolin]# ll decompress/ hehe/ >stdout.txt 2>&1 [root@node01 /home/yangchaolin]# cat stdout.txt
# 错误信息写入 ls: cannot access hehe/: No such file or directory
# 正确信息写入 decompress/: total 20 -rw-------. 1 root root 18311 Oct 20 09:47 secure

输出路径如果写作/dev/null代表输出后不保存,也不在页面打印输出。

(3)标准输入,对应编号0,<为覆盖写,<<为追加写

标准输入有如下操作案例。

# 打印文本中行数
[root@node01 /home/yangchaolin]# wc -l < secure 211
# 将行数打印出来后输出到count [root@node01 /home/yangchaolin]# wc -l < secure > count [root@node01 /home/yangchaolin]# cat count 211
# 可以向user.sql中追加内容,直到用户输入abc字符串才停止 [root@node01 /home/yangchaolin]# cat >> user.sql << 'abc' > select * from user; > select * from user order by id; > insert into user values(null,name,age); > abc # 退出输入
# 查看sql追加到了文件中 [root@node01 /home/yangchaolin]# cat user.sql select * from user; select * from user order by id; insert into user values(null,name,age);

以上是对数据重定向的简单整理。

参考博文:

(1)https://www.jianshu.com/p/d5ea4a8acfb9

原文地址:https://www.cnblogs.com/youngchaolin/p/11715687.html