【问题标题】:Can I pipe part of my bash scripts output to a file? Can I pipe to a file and stdout?我可以将部分 bash 脚本输出通过管道传输到文件吗?我可以通过管道传输到文件和标准输出吗?
【发布时间】:2011-10-05 15:51:00
【问题描述】:

我很确定我以前见过这样做,但我似乎无法通过 google 找到它。

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

如果我可以使用tee 而不是重定向,那就太好了,这样它就会转到那个文件和标准输出。

【问题讨论】:

    标签: bash ksh sh


    【解决方案1】:

    您可以使用至少三种技术中的任何一种。一个由dtmilano 的回答说明,使用完整的子外壳和括号,但要小心破坏以前的输出:

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

    或者您可以使用大括号对 I/O 重定向进行分组,而无需启动子 shell:

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

    或者你有时可以使用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
    

    我通常会使用{ ... } 表示法,但在单行场景中它很古怪; } 必须出现在命令可以开始的位置:

    { ls; date; } >/tmp/x37
    

    这里需要第二个分号。

    【讨论】:

      【解决方案2】:

      我想这就是你想要的

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

      【讨论】:

      • 知道这种技术叫什么吗?此外,回声应该在命令中。没有理由进行两次重定向。
      • 没关系,我的问题令人困惑......这就是你这样做的原因。
      • @Jonathan 可能指的是 echo this should go to the $file > $file 行——这会在 shell 执行 echo 命令之前截断 $file。
      • 好吧——我的错。我会删除我的评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多