【问题标题】:Write to terminal after redirecting stdout to a file without using stderr?将标准输出重定向到文件而不使用标准错误后写入终端?
【发布时间】:2012-03-13 09:28:48
【问题描述】:

我有两个 shell 脚本,一个用作主“程序”,另一个用作“库”。

在“程序”的几个地方,我将执行以下操作:log "$thing" >> "$logfile",其中log 是“库”中定义的函数。

# program.sh

logfile="log.txt"
stuff="hahah heheh hoho"

. library.sh 

for thing in $stuff; do
  log "$thing" >> "$logfile"
done

我的问题:有没有办法使用stderr一些函数的输出重定向回终端而不

# library.sh

log () {

  # This gets written to the log
  echo "`date --rfc-3339=seconds`: $1"

  # How to write this to the terminal *without* using stderr?
  echo "Info: Message written to log." >&2

}

我想避免使用stderr,因为在我的实际程序中,可以选择将错误重定向到文件,但我要发送到终端的消息是信息性的,而不是错误的,并且应该始终显示在终端上。

【问题讨论】:

    标签: bash shell redirect stdout


    【解决方案1】:

    每次想写终端都可以直接写/dev/tty

    echo "hello world" > /dev/tty
    

    举个小例子:

    $ cat writer.sh 
    #!/bin/sh
    
    echo "standard output"
    echo "standard error" >&2
    
    echo "direct to terminal" > /dev/tty
    $ ./writer.sh > /tmp/out 2> /tmp/err
    direct to terminal
    $ cat /tmp/out
    standard output
    $ cat /tmp/err
    standard error
    $ 
    

    【讨论】:

    • 谢谢。我想将这两个都标记为正确,但我必须把这个给 Ignacio 以获取 exec 特殊酱汁:)
    • exec 特制酱汁整洁的。 :)
    【解决方案2】:

    在另一个 FD 上打开 /dev/tty

    exec 0< /dev/null
    exec 1> /dev/null
    exec 2> /dev/null
    exec 3> /dev/tty
    echo 'Hello, World!' >&3 
    

    【讨论】:

    • 有趣...你能解释一下发生了什么吗?另外前三行的意义是什么?它似乎只适用于最后两个。而且,我想我应该把第四行放在program.sh 中,而不是每次调用log 时都执行它?
    • 前三行只是说明原来的描述符现在没用了。它是更复杂程序的简单替代品。
    • 前三个是为了表明脚本没有任何其他方式与外界交谈(例如正忙于做其他事情)。我会将exec 行放在 library.sh 中,但为了以防万一,请给它一个更大的数字(比如 8 左右)。
    • 如果你只是运行man exec,你会得到错误的页面。 man bash,然后搜索短语it replaces the shell。 (在 bash(1) 联机帮助页中搜索 exec 是一种快速发疯的方法。)
    • @GGG:正确;任何符合 POSIX 的 shell 都将提供一个内置的 exec shell。 (嗯,它没有必须内置,但将其作为外部程序提供将非常困难。我能想象的唯一合理的实现是shell-内置的。)我刚刚记得较新的bash 还提供了一个您可能喜欢的help shell-builtin:help exec。它不像联机帮助页那么详细,但可能正是您有一天所需要的。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多