【问题标题】:How to conditionally write the output from a bash scrip to another file?如何有条件地将 bash 脚本的输出写入另一个文件?
【发布时间】:2022-11-17 07:32:54
【问题描述】:

如何根据脚本中的条件将 bash 脚本的输出写入另一个文件?例如,我需要这样的东西

writeToFile=false

read -p "Enter (1-4): "
echo "foo"

if [ $REPLY == "1" ]; then
  echo "writing to file"
  writeToFile=true
fi

如果他们输入 1,那么它应该将输出的所有内容写入文件。如果不是,则不应将任何内容写入文件。

根据我的研究,似乎使用 tee 是正确的方法,但我不知道如何构建它。我试过在 | 中结束文件像这样开球,

{
...
} | tee -a file.txt

但这每次都会写下所有内容。如果我做

{
...
} |
if [ "$writeToFile" = true ]; then
  tee -a $(date +%F).txt
fi

然而那是行不通的。这样做的正确方法是什么?

【问题讨论】:

    标签: bash


    【解决方案1】:

    你可以使用这样的东西

    file='-'
    if [[ "$writeToFile" == true ]]; then
      file='file.txt'
    fi
    
    {
    ...
    } | tee -a "$file"
    

    【讨论】:

      【解决方案2】:

      您可以使用条件 exec 以及进程替换。

      if [[ "$writeToFile" == true ]]
      then
          exec > >(tee -a "$file")
      fi
      

      这之后的所有输出都将写入tee进程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        • 2019-07-16
        • 1970-01-01
        • 2017-01-09
        • 1970-01-01
        • 1970-01-01
        • 2021-11-09
        相关资源
        最近更新 更多