Log background job execution time

You could just use:

time yourscript.sh

But if that doesn't work for you, you can wrap your content of script like:

STARTTIME=$(date +%s)
#command block that takes time to complete...
ENDTIME=$(date +%s)
echo "It takes $($ENDTIME - $STARTTIME) seconds to complete this task..."

Just time the nohup process:

$ time nohup bash -x ~/scripts/foo.sh 
nohup: ignoring input and appending output to 'nohup.out'

real    0m10.011s
user    0m0.005s
sys 0m0.006s

foo.sh simply has sleep 10 as an example.


[this assumes that you want the output of time to also go to log.txt, something which is not clear from your question]

Just don't use nohup.

nohup does nothing special but ignoring the SIGHUP signal, redirecting stdout and stderr to a file and --only in some variants, like the nohup from GNU coreutils-- redirecting the stdin from /dev/null opened in write-only mode.

You can easily do all that from the shell:

{ trap '' HUP; time bash -x your_script args ... ; } > log.txt 2>&1 0>/dev/null &

Or safer, if started from a script or if you don't plan to ever bring back the command to the foreground with fg:

(trap '' HUP; time bash -x your_script args ... 0>/dev/null &) > log.txt 2>&1

(You can omit the 0>/dev/null if you don't care to emulate that feature of GNU nohup).


Of course, you can use the syntax trick from the first example with nohup too if, for some unfathomable reason, you ascribe magical properties to nohup:

{ time nohup bash -x your_script args ... ; } > log.txt 2>&1 &