Using command & + disown instead of nohup

Viewed 1867

I've tried today to use the nohup command to execute an rsync command in order to process the copy of some files from a VM to another even if I close the console.

Then I said why not using rsync [parameters] & + disown %1

What's the difference between the two?

1 Answers

disown is the better practice (being built into the shell rather than depending on an external tool), but it requires more work: You need to redirect stdin, stdout, and stderr yourself (whereas nohup will do the redirection with a nohup.out name hardcoded if you haven't done it yourself).

Thus:

rsync "${args[@]}" </dev/null >logfile 2>&1 & disown -h "$!"

As a stylistic note, if the only use you make of the PID is passing it to disown, I do suggest putting the disown on the same line as the invocation, as done above: This ensures that the $! reference is to the background process forked immediately prior, even if future changes add more code, potentially forking other background processes, after the rsync is started. (On the other hand, if you want to refer to the PID later, you might put a variable assignment on the same line: rsync ... & rsync_pid=$!, then disown -h "$rsync_pid" on a separate line).

Related