本帖最后由 IT邓邓爱踢 于 2019-10-25 13:45 编辑
RHCSA-将输出重定向到文件或程序
1、标准输入、标准输出和标准错误 一个运行的程序(或称为 进程)需要从某个位置读取输入并将输出写入到屏幕或文件。从shell提示符运行的命令通常会从键盘读取其输入,并将输出发送到其终端窗口。 进程使用带编号的通道(称为文件描述符)来获取输入并发送输出。所有进程在开始时至少需具有三个文件描述符: - 标准输入(通道0)——从键盘读取输入;
- 标准输出(通道1)——将正常输出发送到终端;
- 标准错误(通道2)——将错误信息发送到终端。
2、重定向输出到文件
RHCSA-将输出重定向到文件或程序
I/0重定向将默认通道目标位置替换为代表输出文件或设备的文件名。 利用重定向,通常发送到终端窗口的进程输出和错误消息可以捕获为文件内容发送到设备或者丢弃。 输出重定向操作符↓↓↓
RHCSA-将输出重定向到文件或程序
重要 - 重定向操作的顺序非常重要。以下序列将标准输出重定向到file,然后将标准错误作为标准输出重定向到相同位置(file)。
- 但是。下一个序列以相反的顺序执行重定向。这会将标准错误重定向到标准输出的默认位置(终端窗口,因此没有任何更改),然后仅将标准输出重定向到file。
- &>file 而不是 >file 2>&1
- &>>file 而不是 >>file 2>&1(在Bash4 / RHEL6和更高版本中)
复制代码
输出重定向示例
通过重定向,可以简化许多日常管理任务。在思考下列示例时,请参考前面的表格: - [student@desktopX ~]$ date > /tmp/saved-timestamp
复制代码- [student@desktopX ~]$ tail -n 100 /var/log/dmesg >/tmp/last-100-boot-messages
复制代码- [student@desktopX ~]$ cat file1 file2 file3 file4 > /tmp/all-four-in-one
复制代码- [student@desktopX ~]$ ls -a > /tmp/my-file-names
复制代码- [student@desktopX ~]$ eho “new line of information” >> /tmp/many-lines-of-information
- [student@desktopX ~]$ diff previous-file current-file >> /tmp/tracking-changes-made
复制代码- 下列示例中将生成错误,因为普通用户对系统目录的访问会被拒绝。在终端上查看普通命令输出时,将错误重定向到文件。
- [student@desktopX ~]$ find /etc -name passwd 2> /tmp/errors
复制代码- [student@desktopX ~]$ find /etc -name passwd > /tmp/output 2> /tmp/errors
复制代码- [student@desktopX ~]$ find /etc -name passwd > /tmp/output 2> /dev/null
复制代码- [student@desktopX ~]$ find /etc -name passwd &> /tmp/save-both
复制代码- [student@desktopX ~]$ find /etc -name passwd >> /tmp/save-both 2>&1
复制代码
|