输入输出重定向

作者:烟中隐约闪现 | 创建时间: 2023-05-11
既然您在上一个章节中已经学完了几乎所有基础且常用的Linux命令,那么接下来的学习目标就是要将多个Linux命令合适的结合到一起工作,使得咱们的Linux系统在处理数据时更加的高效。而要做到这一点,就特别有必要搞明白命令的输入和输出重定向原...
输入输出重定向

操作方法

比如咱们分别查看两个文件的信息,而第二个文件是不存在的,这样虽然都会在屏幕上输出一些数据信息,但其实差异很大: [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 xxxxxx ls: cannot access xxxxxx: No such file or directory

第一个叫做linuxprobe的文件是存在的,输出信息是该文件的一些相关属性、权限、大小等信息,也是该命令的标准输出信息,而第二个叫做xxxxxx的文件则是不存在的,输出文件的不存在报错提示信息也是该命令的错误输出信息,那么咱们要想将原本输出到屏幕上的数据转向写入到文件当中,就要区别对待这两种输出信息才行。 先来小试牛刀下吧,通过标准输出将“man bash”命令原本要输出到屏幕的信息写入到文件中去,效果类似于: [root@linuxprobe ~]# man bash > readme.txt [root@linuxprobe ~]# cat readme.txt BASH(1)                     General Commands Manual                    BASH(1) NAME bash - GNU Bourne-Again SHell SYNOPSIS bash [options] [file] COPYRIGHT Bash is Copyright (C) 1989-2011 by the Free Software Foundation, Inc. DESCRIPTION Bash  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. ………………省略部分输出信息………………

有没有感觉到特别方便?那么接下来动手试试输出重定向技术中清空写入与追加写入的两种不同模式带来的变化吧~咱们先通过清空模式来向文件写入一行数据(该文件中包含上一个实验的信息),然后再通过追加模式向文件再写入一次数据,最终咱们看到的文件内容会是这个样子的: [root@linuxprobe ~]# echo "Welcome to LinuxProbe.Com" > readme.txt [root@linuxprobe ~]# echo "Quality linux learning materials" >> readme.txt [root@linuxprobe ~]# cat readme.txt Welcome to LinuxProbe.Com Quality linux learning materials

虽然都是输出重定向技术,但对于不同的命令标准输出和错误输出一直却还都有点区别,例如咱们查看下当前目录中某个文件的信息吧。因为这个文件是真实存在的,因此咱们使用标准输出即可将数据写入到文件中,而错误的输出重定向则不行,依然将信息输出到了屏幕上。 [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

那如果是想将命令的报错信息写入到文件呢?例如当您在执行一个自动化的Shell脚本时会特别的实用,因为可以通过将整个脚本执行过程中的报错信息都记录到文件中,便于咱们安装后的排错工作。接下来学习实践中咱们就以一个不存在的文件做演示吧: [root@linuxprobe ~]# ls -l xxxxxx cannot access xxxxxx: No such file or directory [root@linuxprobe ~]# ls -l xxxxxx > /root/stderr.txt cannot access xxxxxx: No such file or directory [root@linuxprobe ~]# ls -l xxxxxx 2> /root/stderr.txt [root@linuxprobe ~]# cat /root/stderr.txt ls: cannot access xxxxxx: No such file or directory

而输入重定向则显得有些冷门,在工作中遇到的机会相对少一点,作用是将文件直接导入到命令中。咱们接下来使用输入重定向将文件导入给“wc -l”命令来统计下内容行数吧,这样命令其实等同于接下来要学习的“cat readme.txt | wc-l”的管道符命令组合。 [root@linuxprobe ~]# wc -l < readme.txt 2

点击展开全文

更多推荐