zoukankan      html  css  js  c++  java
  • 文件描述符

    创建输出文件描述符
    $ cat test13
    #!/bin/bash
    # using an alternative file descriptor
    exec 3>test13out
    echo "This should display on the monitor"
    echo "and this should be stored in the file" >&3
    echo "Then this should be back on the monitor"
    $ ./test13
    This should display on the monitor
    Then this should be back on the monitor
    $ cat test13out
    and this should be stored in the file
    $
    这个脚本用exec命令将文件描述符3重定向到另一个文件。当脚本执行echo语句时,输出内 容会像预想中那样显示在STDOUT上。但你重定向到文件描述符3的那行echo语句的输出却进入 了另一个文件。这样你就可以在显示器上保持正常的输出,而将特定信息重定向到文件中(比如 日志文件)。
    也可以不用创建新文件,而是使用exec命令来将输出追加到现有文件中。
    exec 3>>test13out
    现在输出会被追加到test13out文件,而不是创建一个新文件。
     
    重定向文件描述符
    将文件描述符3 重定向到标准输出 1,
    将标准输出1 重定向到 test14out文件
    将标准输出1 重定向到文件描述符3
     
    $ cat test14
    #!/bin/bash
    # storing STDOUT, then coming back to it
    exec 3>&1
    exec 1>test14out
    echo "This should store in the output file"
    echo "along with this line."
    echo "and this should be stored in the file" >&3
    exec 1>&3
    echo "Now things should be back to normal"
    echo "xxxxxxxxxxx" >&3
    $ ./test.sh
    and this should be stored in the file
    Now things should be back to normal
    xxxxxxxxxxx
    $
    $
    $ cat test14out
    This should store in the output file
    along with this line.
    $
     
     
    创建输入文件描述符
    文件描述符6用来保存STDIN的位置。然后脚本将STDIN重定向到一个文件。 read命令的所有输入都来自重定向后的STDIN(也就是输入文件)。
    在读取了所有行之后,脚本会将STDIN重定向到文件描述符6,从而将STDIN恢复到原先的 位置。该脚本用了另外一个read命令来测试STDIN是否恢复正常了。这次它会等待键盘的输入。
     
    $ cat test15
    #!/bin/bash
    # redirecting input file descriptors
    exec 6<&0
    exec 0< testfile
    count=1
    while read line
    do
    echo "line #$count :$line"
    count=$[ $count + 1 ]
    done
    exec 0<&6
    read -p "Are you done now? " answer
    case $answer in
    Y|y) echo "Goodbye";;
    N|n) echo "Sorry, this is the end.";;
    esac
    $
    $ ./test15
    Line #1: This is the first line.
    Line #2: This is the second line.
    Line #3: This is the third line.
    Are you done now? y
    Goodbye
    $
     
     
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    js 格式化时间
    javascript Base64 加密解密方法
    为什么给元素添加了z-index却没有效果
    浮动 与 清除浮动
    Vue 介绍 以及 学习总结(这里不详细展开)
    redux 的基础用法
    c# 几种深拷贝方式的比较
    C#四种深拷贝方法
    Innershar C#中Skip和Take的用法
    DataTable.AcceptChanges方法有何用处
  • 原文地址:https://www.cnblogs.com/sea-stream/p/13527659.html
Copyright © 2011-2022 走看看