Linux – nohup multiple sequential commands

linuxnohup

I need to nohup two commands, one after another. The second command has to be executed AFTER the first command. Here are the commands:

tar -zcf archive.tar.gz.tmp mydir
mv archive.tar.gz.tmp archive.tar.gz

I need the commands to run in the background, but obviously not both at the same time. The second command has to be run after the first command is complete. I tried this:

nohup tar -zcf archive.tar.gz.tmp mydir ; mv archive.tar.gz.tmp archive.tar.gz > /dev/null 2>&1 &

but the commands don't run in the background. The bash prompt waits until the two commands are complete before giving me another prompt. I need them to run in the background.

If I do:

nohup tar -zcf archive.tar.gz.tmp mydir > /dev/null 2>&1 &

That runs in the background perfectly. It's only when I try to do more than one command.

I also tried:

nohup tar -zcf archive.tar.gz.tmp mydir > /dev/null 2>&1 & ; mv archive.tar.gz.tmp archive.tar.gz > /dev/null 2>&1 &

But that didn't work either. Invalid syntax or something. I'm sure there is a way to do this but I'm just not sure the syntax.

The only alternative I can think of is to put the commands into a .sh file and nohup that file, but that isn't necessarily something I can do on the linux system I have to implement this on (privileges limitations etc).

Best Answer

Easiest solution: Create a shell script with

 #/bin/sh
 tar -zcf archive.tar.gz.tmp mydir
 mv archive.tar.gz.tmp archive.tar.gz

And use nohup myscript. Possibly with some extra documentation in the script.

(Yes, I am a sucker for documentation. Especially when working with multiple people or when you might someday leave the job and your successor needs to figure out why".)


An alternative might be to start a new shell for a subtask (in this case your tar and move)

nohup `$(tar -zcf archive.tar.gz.tmp mydir; mv archive.tar.gz.tmp archive.tar.gz)


Alternative 2:

nohup ```tar -zcf archive.tar.gz.tmp mydir ; mv archive.tar.gz.tmp archive.tar.gz```.

I really prefer the script though. The comments in it might be quite useful when you or someone else looks at he script in a few years and wonders why it was done this way.

On a unrelated note: How the heck do I post an anser with a backtick in it? (The command for a shell to 'use this command ; feed the output to another command as input`).