bc81 bc81 - 1 year ago 56
Linux Question

How to get printf to write a new file, append an existing file, and write to stdout?

I have a

command that will write a file but won't print to stdout. I would like to have both so I can let the user see what's happening, and at the same time, write a record to a log file.

printf "%s\n" "This is some text" "That will be written to a file" "There will be several lines" | tee -a bin/logfile.log > bin/newfile.conf

That command appends to the log file and writes to the new file, but writes no output to the screen :(

OS: Centos 7

Answer Source

It's because you're redirecting the screen output with > bin/newfile.conf in addition to what you're doing with tee. Just drop the > and everything after it. If you want to output to both of those files at once in addition to the screen, you can use tee twice, e.g.:

printf ... | tee -a bin/logfile.log | tee bin/newfile.conf

That appends to logfile.log and overwrites newfile.conf, and also writes out to the screen. Use or omit the -a option as needed.

As John1024 points out you can also use tee once since it accepts multiple filenames, although in that case -a applies to all filenames, but it can be useful in the case where you want the append vs. overwrite behavior to be the same for all files.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download