Ethan Ethan - 7 months ago 31
Linux Question

Run multiple commands in serial and make sure all commands run

I want to run a series of unix commands, one after another. If any of these commands dies for whatever reason, subsequent commands should continue to run.

For instance, I have 3 commands called "setup", "long-running-job" and "teardown". If "long-running-job" finishes with whatever exit code, or dies unexpectedly, I want to make sure "teardown" gets run in any case.

Simply concatenating all commands with semicolons doesn't seem to work. I tried running

touch test.txt; ping localhost; rm test.txt
in macOS Terminal, closed the terminal tab while it's running, and found that the "test.text" didn't get removed.


If you want to make sure that even if your interactive window closes that your commands keep going and that all your command happen sequentially in the order you specify then use the method in this answer:

Basically for the command line in your question

nohup sh -c 'touch test.txt; ping localhost; rm test.txt'

That means the hang up signal sent by closing the terminal is ignored.