Bash – Log Background Job Execution Time

background-processbashtime

I have a script I execute in the background and capture all output with a command like this:

nohup bash -x test.sh < /dev/null > log.txt 2>&1 &

How can I find out how long it took to complete? If I try to use time after bash -x I get an error:

/usr/bin/time: /usr/bin/time: cannot execute binary file

If I try to use acct it doesn't seem to log the process or I can't find it.

Best Answer

[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 &
Related Question