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
    
  • 相关阅读:
    可变参数模板的递归解析
    在Ubuntu上安装多个版本的g++ 并进行默认版本切换
    不错的威盾PHP加密专家解密算法
    文章相关性分析详细介绍
    c#连接mysql中文乱码解决方案(MySql.Data.dll)
    firefox用12306Helper 0.2结合ie tab+自动订火车票和完成支付全攻略
    Nutch命令大全
    Jtable利用SetModel进行数据绑定
    在php中使用CKEDITOR在线编辑器
    Nutch1.2搜索引擎使用详解
  • 原文地址:https://www.cnblogs.com/scf141592/p/5308496.html
Copyright © 2011-2022 走看看