我正在做一个脚本,执行一些命令里面,这些命令显示一些输出在STDOUT (和STDERR以及,但这是没有问题的)。 我需要我的脚本生成一个.tar.gz文件到STDOUT ,所以在脚本中执行的一些命令的输出也转到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/
我已经尝试搞清楚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/
我想我没有closuresSTDOUT后第一个EXEC再次打开它或什么,但我找不到正确的方法来做到这一点(现在结果是一样的,如果我没有添加exec
标准输出是屏幕。 标准输出和“屏幕”之间没有分离。
在这种情况下,我只是将stdoutredirect到stderr,在一个子shell中1>&2 。 这将导致命令的输出显示在屏幕上,但不会在程序的标准输出stream。
#!/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/
是否有一个原因,你需要pipe这个脚本的输出到别的东西? 通常情况下,您只需使用-f标志将tar写入文件,或者仅对tar命令执行redirect: tar zc whatever > filename.tar.gz (除非将它放到设备上,例如磁带或使用它作为副本的一种forms)。
如果使用tar命令的-f开关来告诉tar写入文件,会不会更容易?
tar zcf whatever.tar.gz whatever/
如果这样做没有做到你想要的,那么你将不得不单独redirect每个可能写入标准input的命令
some_cmd foo bar 1>&2
我想你正在寻找某种多路复用。
这是一个简单的例子,如何将时间戳添加到每条标准输出行: http : //www.podciborski.co.uk/programming/perl/add-a-timestamp-to-every-stdout-line/
您可以使用一些特殊的标记而不是时间戳来标记日志行。 比你不得不删除另一端的那些线。 所以用法是这样的:
ssh user@remoteserver the_script.sh | create_tar.sh filename
create_tar.sh应该是脚本,用日志标记打印行并将另一行redirect到文件。