• 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
    
  • 相关阅读:
    联合索引和多个单列索引选择
    CentOS6.5 一台服务器同时安装多个Mysql数据库
    一次CentOS的服务器被攻击教训
    java版本的memcache静态化
    mysql存储空间满的处理方式
    MariaDB 10.0 和 MariaDB 10.1 存储过程中 PREPARE FROM EXECUTE 区别
    CentOS6.x 优化脚本
    Mysql 使用 “LOAD DATA INFILE”需要注意的问题
    Mysql 日期类型比较 TIMESTAMPDIFF
    CentOS6.x 源码安装Nginx
  • 原文地址:https://www.cnblogs.com/scf141592/p/5308496.html
Copyright © 2020-2023  润新知