Outputting Errors to a Log file

Good Morning,

Every so often, I have copy scripts that to don't complete, but I don't immediately know why. It usually ends up being a permissions issue or a length issue.

The scripts edit a log file, so I'd like to include any copy errors/issues in that file to check if the copies ran into issues. I'm thinking:

cp -R /dir/dir/dir /dir2/dir2/dir2 2>&1 | printf /dir/dir/logfile

Will this work and/or is there something better? Will it work even if the script fails to complete the copy?

printf does not open and print a file you want cat

cp -R /dir/dir/dir /dir2/dir2/dir2 2>&1 || cat /dir/dir/logfile

This only displays logfile when there is an error, which I guess is what you want. Note the double pipe.

1 Like

Just as a FWIW. Copying files like that appears to be some kind of a backup attempt.
Not a great idea.

This may not be what you think it is. So. One thing I would consider seriously - simply for saving disk space and short term only- backup to a compressed tarball and possibly on another physically separate disk. For data security improvement.

e.g., tar cfz /path/tar_$(date '+%Y%m%d).tgz /dir/dir/dir
linux tar example

Move the tarballs offsite on storage media like tape after a week (or month) if they are truly important. Scheduling this is a business/legal decision....

1 Like

Thanks. Just to be clear, I don't want to display the log file. I want the existing log file (text document) to record any errors that happened during copying. Does this do that? Also, why the double pipe? This means do the second command if the first failed- correct? What are the two commands?

cp doesn't write to stdout unless told so by e.g. the -v option. All error messages go to stderr. Try

cp -R /dir/dir/dir /dir2/dir2/dir2 2>/dir/dir/logfile