1

This question already has an answer here:

I have a BASH utility that outputs measurements to screen live as it runs and writes the result to file at the same time. I am having to repeat the same code twice (see below).

Once to write to screen, and

Once to write to file.

This seems like a lot of redundancy to me.

Can I put one text block into something like a function then call it to be written to screen and file at the same time?

This would cut down on a lot of re-keying.

Example below

###### write out to file : push end time at end ################
echo >> $file_name
echo "End time: "$end_time >> $file_name
echo >> $file_name
echo >> $file_name
echo >> $file_name

######  print to screen : push end time at end  #################

echo 
echo "End time: "$end_time 
echo
echo
echo

So I'd be looking for someting like this

funtion text_block{
######  print to screen : push end time at end  #################
echo 
echo "End time: "$end_time 
echo
echo
echo
}

Then a command that does something like this

"command print text_block to screen, print text_block to file"

marked as duplicate by Kiwy, Rui F Ribeiro, Christopher, roaima, Mr Shunz Jan 16 at 9:06

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

You can use the utility tee

command | tee my_file.out  

this will both write a file name my_file.out and write it to stdout.

Source this post from StackOverflow

  • that really helped me clean up repeat code and get rid of typos introduced by unnecessary re-keying when making changes. Thanks – Kes Jan 15 at 13:37
  • You're very welcome @Kes – Kiwy Jan 15 at 14:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.