Reputation: 103
I have a bash script that does some data copy and some transformations. The script can run for several minutes depending on the file size. In the meantime, another process can trigger this script to copy its files.
I want to maintain individual log for each run of the script. Is it possible?
Upvotes: 3
Views: 1891
Reputation: 133538
Here is an example script(I created for an example) whose logs will be written to a log file based on date and time each time it runs:
cat check_script.ksh
CURRENT_TIME=$(date +%d-%m-%Y-%H:%M-%S)
echo "Running copy command now..." > "$CURRENT_TIME.txt"
## cp command here......
echo "Running another comand now....." >> "$CURRENT_TIME.txt"
## Bla bla bla
echo "Scrpit is completed..." >> "$CURRENT_TIME.txt"
EDIT: Also to check either your script is already running or not, let's do the OLD school logic create Watch Dog file(a lock file kind of) at the starting of script(if it is already not created, put check first if it is NOT created or present then create it or exit the program considering that it is running) and every time script completes(after your last successful command) you could delete it then, if your next runs come and sees that file is there it should exit from the script then.
Upvotes: 1
Reputation: 10138
You could write your logs to a file whose name is based on:
PID
of your program's instanceThis should be enough to make sure each instance of your program has its own log file.
Here is a small example:
pid=$(echo $$) # Current instance PID
date=$(date +%s) # Seconds since Epoch
logfile="myscript.$date.$pid.log"
echo "I'm a log" > $logfile
echo "I'm another log" >> $logfile
If you want to include the name of the process that triggered your script, you could pass it as an argument to your script, like this:
myscript.sh
parent="$1"
pid=$(echo $$)
date=$(date +%s)
logfile="myscript.$date.$pid.$parent.log"
echo "I'm a log" > $logfile
echo "I'm another log" >> $logfile
You would call this script like this:
sh myscript.sh parent_script_name
And it would create a file similar to this one:
myscript.1518358314.85866.parent_script_name.log
Upvotes: 0