Hokerie
Hokerie

Reputation: 2595

Create a detailed self tracing log in bash

I know you can create a log of the output by typing in script nameOfLog.txt and exit in terminal before and after running the script, but I want to write it in the actual script so it creates a log automatically. There is a problem I'm having with the exec >>log_file 2>&1 line:

The code redirects the output to a log file and a user can no longer interact with it. How can I create a log where it just basically copies what is in the output?

And, is it possible to have it also automatically record the process of files that were copied? For example, if a file at /home/user/Deskop/file.sh was copied to /home/bckup, is it possible to have that printed in the log too or will I have to write that manually?

Is it also possible to record the amount of time it took to run the whole process and count the number of files and directories that were processed or am I going to have to write that manually too?

My future self appreciates all the help!

Here is my whole code:

#!/bin/bash    

collect()
{
find "$directory" -name "*.sh" -print0 | xargs -0 cp -t ~/bckup #xargs handles files names with spaces. Also gives error of "cp: will not overwrite just-created" even if file didn't exist previously
}
echo "Starting log"
exec >>log_file 2>&1
timelimit=10
echo "Please enter the directory that you would like to collect.
If no input in 10 secs, default of /home will be selected"

read -t $timelimit directory

if [ ! -z "$directory" ] #if directory doesn't have a length of 0
then
echo -e "\nYou want to copy $directory." #-e is so the \n will work and it won't show up as part of the string
else
directory=/home/
echo "Time's up. Backup will be in $directory"
fi

if [ ! -d ~/bckup ]
then
echo "Directory does not exist, creating now"
mkdir ~/bckup
fi 

collect
echo "Finished collecting"

exit 0

Upvotes: 0

Views: 271

Answers (1)

Martin Mrazik
Martin Mrazik

Reputation: 386

To answer the "how to just copy the output" question: use a program called tee and then a bit of exec magic explained here: redirect COPY of stdout to log file from within bash script itself

Regarding the analytics (time needed, files accessed, etc) -- this is a bit harder. Some programs that can help you are time(1):

time - run programs and summarize system resource usage

and strace(1):

   strace - trace system calls and signals

Check the man pages for more info. If you have control over the script it will be probably easier to do the logging yourself instead of parsing strace output.

Upvotes: 1

Related Questions