Reputation: 35
I have a shell script that calls 2 other scripts that take many positional parameters.
Main Script
LOGFILE="status.log"
TIMESTAMP="`date "+%Y-%m-%d %H:%M:%S"` $BASH_SOURCE : "
sudo ./call_script_A arg1 arg2
echo "$TIMESTAMP task 1 complete" | tee -a $LOGFILE
sudo ./call_script_B arg1 arg2 arg3
echo "$TIMESTAMP task 2 complete" | tee -a $LOGFILE
.
.
.
sudo ./call_script_A arg1 arg2 arg3 arg4
echo "$TIMESTAMP task n complete" | tee -a $LOGFILE
And the output log from the above script after several hours was:
2020-08-28 09:44:43 ./main_script.sh : task 1 complete
2020-08-28 09:44:43 ./main_script.sh : task 2 complete
2020-08-28 09:44:43 ./main_script.sh : task 3 complete
2020-08-28 09:44:43 ./main_script.sh : task 4 complete
2020-08-28 09:44:43 ./main_script.sh : task 5 complete
2020-08-28 09:44:43 ./main_script.sh : task n complete
Notice how the timestamps stay constant despite the fact that its been echo'd several times in the main script above?
On all my scripts, i have the below 2 lines.
LOGFILE="status.log"
TIMESTAMP="`date "+%Y-%m-%d %H:%M:%S"` $BASH_SOURCE : "
How do I debug this situation considering the fact that I am using these variables across all my scripts?
Upvotes: 0
Views: 1036
Reputation: 15293
The subshell evaluates before assigning the variable. What you want is a function.
$: logfile="status.log"
$: Log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') $BASH_SOURCE : $@" | tee -a $logfile
}
$: Log task 1 complete
2020-08-28 13:44:58 main : task 1 complete
$: cat status.log
2020-08-28 13:44:58 main : task 1 complete
$: Log "task 2 complete"
2020-08-28 13:45:26 main : task 2 complete
$: cat status.log
2020-08-28 13:44:58 main : task 1 complete
2020-08-28 13:45:26 main : task 2 complete
$: Log "task 3 complete"
2020-08-28 13:49:28 main : task 3 complete
$: cat status.log
2020-08-28 13:44:58 main : task 1 complete
2020-08-28 13:45:26 main : task 2 complete
2020-08-28 13:49:28 main : task 3 complete
Upvotes: 2