将输出重定向到终端

时间:2015-07-16 12:38:30

标签: bash echo stdout stderr io-redirection

我想了解重定向输出。

我有代码:

#!/bin/bash
function function1 () {
    log=${1}.log

    exec 3>&1
    exec 1>>$log
    exec 2>&1

    echo checking $log >&3
    echo txt to $log
}

function1 log1
function1 log2

exit 0

我得到的输出是:

checking log1.log

和文件log1.log包含内容

txt to log1.log
checking log2.log

和文件log2.log包含内容

txt to log2.log

我真正想要的是文件log1.log的内容

txt to log1.log

和文件log2.log包含内容

txt to log2.log

并输出到终端。

checking log1.log
checking log2.log

我该怎么办呢? 我知道我可以使用function1 log1 > log1.log 2>&1,但是我无法将echo重定向到function1中的终端,我可以,但结果类似。

2 个答案:

答案 0 :(得分:1)

这应该这样做

#!/bin/bash
function function1 () {
    log=${1}.log

    echo checking $log
    echo txt to $log >$log
}

function1 log1
function1 log2

exit 0

当您仅使用更改过的目标一次时,没有理由将更改存储到任何特定的文件描述符。

如果您确实想使用这种方法,比如因为您重定向了很多命令,那么您至少有两个选项:

  • 在子shell中运行重定向和关联命令,这样当它退出时,您仍然处理原始流
  • 将重定向视为寄存器保存在函数调用中 - 将它们推送到临时(如上面的&3中),然后在调用后将其恢复。

答案 1 :(得分:1)

不知道你为什么要这样做,另一个答案是一个更好的方法,除非你没有透露所有信息,但问题在于你对文件描述符的工作原理的理解。

第一次

exec 3>&1     ## Assign 3 to where 1 is currently pointing which is /dev/tty
exec 1>>$log  ## assigns 1 to point to logfile
exec 2>&1     ## Assigns stderr to the 1 which currently points at the logfile

第二次

exec 3>&1     ## Assign 3 to where 1 is currently pointing which is the old logfile
exec 1>>$log  ## assigns 1 to point to new logfile
exec 2>&1     ## Assigns stderr to the 1 which currently points at the new logfile

正如您所看到的那样,文件描述符会记住它们指向的位置并简单地指向您告诉它们的任何内容。

如果你想这样做,而不是重定向到1,只需直接重定向到/ dev / tty,不像1,这将永远不会改变(希望!)。

#!/bin/bash
function function1 () {
    log=${1}.log

    exec 3>/dev/tty
    exec 1>>$log
    exec 2>&1


    echo checking $log >&3
    echo txt to $log

    exec 1>/dev/tty # Probably want this line as well so your not writing to 
                    #  the logfile for the rest of the script
} 

function1 log1
function1 log2

exit 0
相关问题