输入输出重定向
1、比如咱们分别查看两个文件的信息,而第二个文件是不存在的,这样虽然都会在屏幕上输出一些数据信息,但其实差异很大:[root@linuxprobe ~]# touch linuxprobe[root@linuxprobe ~]# ls -l linuxprobe-rw-r--r--. 1 root root 0 Aug 5 05:35 linuxprobe[root@linuxprobe ~]# ls -l xxxxxxls: cannot access xxxxxx: No such file or directory
2、第一个叫做linuxprobe的文件是存在的,输出信息是该文件的一些相关属性、权限、大小等疙熳阊涓信息,也是盐淬芪求该命令的标准输出信息,而第二个叫做xxxxxx的文件则是不存在的,输出文件的不存在报错提示信息也是该命令的错误输出信息,那么咱们要想将原本输出到屏幕上的数据转向写入到文件当中,就要区别对待这两种输出信息才行。先来小试牛刀下吧,通过标准输出将“man bash”命令原本要输出到屏幕的信息写入到文件中去,效果类似于:[root@linuxprobe ~]# man bash > readme.txt[root@linuxprobe ~]# cat readme.txtBASH(1) General Commands Manual BASH(1)NAMEbash - GNU Bourne-Again SHellSYNOPSISbash [options] [file]COPYRIGHTBash is Copyright (C) 1989-2011 by the Free Software Foundation, Inc.DESCRIPTIONBash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incor‐ porates useful features from the Korn and C shells (ksh and csh).Bash is intended to be a conformant implementation of the Shell and Utilities portion of the IEEE POSIX specification (IEEE Standard 1003.1).Bash can be configured to be POSIX-conformant by default.………………省略部分输出信息………………
3、有没有感觉到特别方便?那么接下来动手试试输出重定向技术中清空写入与追加写入的两种不同模式带来的变化吧~咱们先通过清空模式来向文件写入一行数据(该文件中包含上一个实验的信息),然后再通过追加模式向文件再写入一次数据,最终咱们看到的文件内容会是这个样子的:[root@linuxprobe ~]# echo "Welcome to LinuxProbe.Com" > readme.txt [root@linuxprobe ~]# echo "Quality linux learning materials" >> readme.txt[root@linuxprobe ~]# cat readme.txtWelcome to LinuxProbe.ComQuality linux learning materials
4、虽然都是输出重定向技术,但对于不同的命令标准输出和错误输出一直却还都有点区别,例如咱们查看下当前目录中某个文件的信息吧。因为这个文件是真实存在的,因此咱们使用标准输出即可将数据写入到文件中,而错误的输出重定向则不行,依然将信息输出到了屏幕上。[root@linuxprobe ~]# ls -l linuxprobe-rw-r--r--. 1 root root 0 Mar 1 13:30 linuxprobe[root@linuxprobe ~]# ls -l linuxprobe > /root/stderr.txt[root@linuxprobe ~]# ls -l linuxprobe 2> /root/stderr.txt-rw-r--r--. 1 root root 0 Mar 1 13:30 linuxprobe
5、那如果是想将命令的报错信息写入到文件呢?麻质跹礼例如当您在执行一个自动化的Shell脚本时会特别的实用,因为可以通过将整个脚本执行过程中的报错信息都记录到文件中,便于咱们安装后的排错工作。接下来学习实践中咱们就以一个不存在的文件做演示吧:[root@linuxprobe ~]# ls -l xxxxxxcannot access xxxxxx: No such file or directory[root@linuxprobe ~]# ls -l xxxxxx > /root/stderr.txtcannot access xxxxxx: No such file or directory[root@linuxprobe ~]# ls -l xxxxxx 2> /root/stderr.txt[root@linuxprobe ~]# cat /root/stderr.txtls: cannot access xxxxxx: No such file or directory
6、而输入重定向则显得有些冷门,在工作中遇到的机会相对少一点,作用是将文件直接导入到命令中。咱们接下来使用输入重定向将文件导入给“wc -l”命令来统计下内容行数吧,这样命令其实等同于接下来要学习的“cat readme.txt | wc-l”的管道符命令组合。[root@linuxprobe ~]# wc -l < readme.txt2