zoukankan      html  css  js  c++  java
  • shell文件描述符及重定向

      文件描述符是与文件输入、输出相关联的整数。它用来跟踪已经打开的文件。最常见的文件描述符是stdin、stdout、stderr。我们甚至可以将某个文件描述的内容重定向到另一个文件描述符中。文件描述符0,1,2是系统预留的:

    0----stdin(标准输入)  1----stdout(标准输出)  2----stderr(标准错误)

    实例

    (一)、将输出的文本重定向到一个文件中:

    [root@localhost shell]# echo "this is a example test"> temp.txt
    You have new mail in /var/spool/mail/root
    [root@localhost shell]# cat temp
    cat: temp: 没有那个文件或目录
    [root@localhost shell]# cat temp.txt
    this is a example test
    [root@localhost shell]# echo this is a example test> temp.txt
    [root@localhost shell]# cat temp.txt
    this is a example test
    [root@localhost shell]# echo 'this is a example test'> temp.txt
    [root@localhost shell]# cat temp.txt
    this is a example test
    

      (二)、将文本追加到目标文件

    [root@localhost shell]# echo 'this is a example test'>> temp.txt
    [root@localhost shell]# cat temp.txt
    this is a example test
    this is a example test
    [root@localhost shell]# echo this is a example test>> temp.txt
    [root@localhost shell]# cat temp.txt
    this is a example test
    this is a example test
    this is a example test
    

      (三)、cat 文件名 :查看文件的内容

      (四)、标准错误的重定向,当命令输出错误信息时,stderr信息就会被打印出来

    [root@localhost shell]# ls +
    ls: 无法访问 +: 没有那个文件或目录
    [root@localhost shell]# echo $?
    2
    [root@localhost shell]# ls + > out.txt
    ls: 无法访问 +: 没有那个文件或目录
    [root@localhost shell]# ls + 2> out.txt
    [root@localhost shell]# cat out.txt
    ls: 无法访问 +: 没有那个文件或目录
    

      第一次的ls + 中的+是非法参数,因此命令将执行失败;

      echo $? 能输出上个命令执行后状态;

      第三句的ls + >out.txt将执行失败的信息输出到了屏幕,并不是文件中,最后一句加上文件描述符才输出到了文件中,然后可以查看到文件的内容;

      (五)、自定义文件描述符

      创建文件描述符进行文件读取;

      

    root@localhost shell]# echo this is s test > input.txt
    [root@localhost shell]# exec 3< input.txt
    [root@localhost shell]# cat &3
    [1] 8171
    bash: 3: command not found
    [root@localhost shell]# cat 3
    cat: 3: 没有那个文件或目录
    
    [1]+  Stopped                 cat
    [root@localhost shell]# cat <&3
    this is s test
    
  • 相关阅读:
    div中嵌套div中使用margin-top失效问题
    thinkphp点击导航变色
    thinkphp I() 方法
    判断是手机端还是电脑端 isMobile()
    手机端H5 header定义样式
    AR.Drone 2.0四轴飞机体验:最好的玩具航拍器
    这是一个专注于电脑技术、软件应用、互联网、嵌入式,电子技术行业等的原创IT博客
    ul li列子
    [HTML]去除li前面的小黑点,和ul、LI部分属性
    Bad update sites
  • 原文地址:https://www.cnblogs.com/scf141592/p/5308496.html
Copyright © 2011-2022 走看看