Home > OS >  How to conditionally write the output from a bash scrip to another file?
How to conditionally write the output from a bash scrip to another file?

Time:11-17

How can I write the output of a bash script to another file based on a condition in the script? for example, I need something like this

writeToFile=false

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

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

if they enter 1, then it should write everything that was outputted to a file. If not, then nothing should be written to a file.

From my research it seem like using tee is the correct way to go, but I cant figure out how to structure it. I have tried ending the file in | tee like so,

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

but that writes everything every time. If I do

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

however that does not work. What is the correct way to do this?

CodePudding user response:

You can use a conditional exec along with process substitution.

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

All the output after this will be written to the tee process.

CodePudding user response:

You can use something like this

file='/dev/null'
if [[ "$writeToFile" == true ]]; then
  file='file.txt'
fi

{
...
} | tee -a "$file"

edit

@Charles Duffy: thanks for pointing it out

  •  Tags:  
  • bash
  • Related