暂时将 STDOUT 重定向到另一个文件描述符,但仍会重定向到屏幕

Car*_*rós 2 linux shell bash redirection stdout

我正在制作一个在内部执行一些命令的脚本,这些命令显示一些输出STDOUTSTDERR以及,但这没问题)。我需要我的脚本生成一个 .tar.gz 文件到STDOUT,所以脚本中执行的一些命令的输出也会转到STDOUT,这以输出中无效的 .tar.gz 文件结束。

因此,简而言之,可以将第一个命令输出到屏幕(因为我仍然想看到输出)但不能通过STDOUT? 此外,我想保持STDERR原样,以便那里只显示错误消息。

我的意思的一个简单例子。这将是我的脚本:

#!/bin/bash

# the output of these commands shouldn't go to STDOUT, but still appear on screen
some_cmd foo bar
other_cmd baz

#the following command creates a tar.gz of the "whatever" folder,
#and outputs the result to STDOUT
tar zc whatever/
Run Code Online (Sandbox Code Playgroud)

我试过搞乱exec文件描述符,但我仍然无法让它工作:

#!/bin/bash

# save STDOUT to #3
exec 3>&1

# the output of these commands should go to #3 and screen, but not STDOUT
some_cmd foo bar
other_cmd baz

# restore STDOUT
exec 1>&3

# the output of this command should be the only one that goes to STDOUT
tar zc whatever/
Run Code Online (Sandbox Code Playgroud)

我想我STDOUT在第一个 exec 之后缺少关闭并再次重新打开它或其他什么,但我找不到正确的方法来做到这一点(现在结果与我没有添加execs 一样

web*_*toe 5

标准输出是屏幕。标准输出和“屏幕”之间没有分离。

在这种情况下,我只是将 stdout 临时重定向到1>&2一个 subshel​​l 中的stderr 。这将导致命令的输出显示在屏幕上,但不会出现在程序的标准输出流中。

#!/bin/bash

# the output of these commands shouldn't go to STDOUT, but still appear on screen

# Start a subshell
(
    1>&2                # Redirect stdout to stderr
    some_cmd foo bar
    other_cmd baz
)
# At the end of the subshell, the file descriptors are 
# as they usually are (no redirection) as the subshell has exited.

#the following command creates a tar.gz of the "whatever" folder,
#and outputs the result to STDOUT
tar zc whatever/
Run Code Online (Sandbox Code Playgroud)

您是否需要将此脚本的输出通过管道传输到其他内容中?通常,您只需使用 tar-f标志将 tar 写入文件或仅对 tar 命令执行重定向:(tar zc whatever > filename.tar.gz除非您将其放入磁带等设备或将其用作副本形式)。