开发者

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.


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:

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:

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 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; the } must appear where a command could start:

{ ls; date; } >/tmp/x37

The second semicolon is needed there.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜