简体   繁体   English

我可以将部分bash脚本输出传输到文件吗? 我可以管道到文件和标准输出?

[英]Can I pipe part of my bash scripts output to a file? Can I pipe to a file and stdout?

I am pretty sure I've seen this done before, but I can't seem to find it by google. 我很确定我之前已经看过这个,但我似乎无法通过谷歌找到它。

for file in $mydir/*
do
    #redirect the rest to $myotherdir/$file.output.
    echo this should go to the $myotherdir/$file.output.
done

It would also be great if I could use tee instead of a redirect, so that it goes to that file and stdout. 如果我可以使用tee而不是重定向,那么它也会很棒,因此它会转到该文件和stdout。

I think this is what you want 我想这就是你想要的

for file in $mydir/*
do
   (
     commands
     ...
   ) > /$myotherdir/$file.output
   echo this should go to the $file > $file
done

You can use any of at least three techniques. 您可以使用至少三种技术中的任何一种。 One is illustrated by dtmilano 's answer, using a full sub-shell and parentheses, but be careful about clobbering previous output: 一个是由dtmilano的回答说明的,使用完整的子shell和括号,但要小心破坏以前的输出:

outfile=/$myotherdir/$file.output

for file in $mydir/*
do
    (
    ...commands...
    ) >> $outfile
    ...other commands with output going elsewhere...
done

Or you can use braces to group the I/O redirection without starting a sub-shell: 或者,您可以使用大括号对I / O重定向进行分组,而无需启动子shell:

outfile=/$myotherdir/$file.output

for file in $mydir/*
do
    {
    ...commands...
    } >> $outfile
    ...other commands with output going elsewhere...
done

Or you can sometimes use exec : 或者你有时可以使用exec

exec 1>&3    # Preserve original standard output as fd 3
outfile=/$myotherdir/$file.output

for file in $mydir/*
do
    exec 1>>$outfile
    ...standard output
    exec 1>&3
    ...other commands with output going to original stdout...
done

I'd normally use the { ... } notation, but it is cranky in a 1-line scenario; 我通常使用{ ... }符号,但它在1行场景中是胡思乱想的; the } must appear where a command could start: }必须出现在命令可以启动的位置:

{ ls; date; } >/tmp/x37

The second semicolon is needed there. 那里需要第二个分号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM