8

I read about the following 2 ways to run multiple commands in a single cron job:

We can run several commands in the same cron job by separating them with a semi-colon (;).

* * * * * /path/to/command-1; /path/to/command-2

If the running commands depend on each other, we can use double ampersand (&&) between them. As a result, the second command will not be executed if the first one fails.

* * * * * /path/to/command-1 && /path/to/command-2

My requirements are:

  • the commands must be executed sequentially (wait for the current one to complete before executing the next one)
  • the commands must be executed in the given order
  • but every command should be executed, even if the previous one failed

What the link above therefore doesn't say is:

Does the semicolon ; approach still guarantees that the commands will be executed sequentially, and in the given order?

BenMorel
  • 4,587

1 Answers1

9

Yes, using ; between the commands will guarantee that all commands are run sequentially, one after the other. The execution of one command would not depend on the exit status of the previous one.

As pointed out by Paul_Pedant in comments, doing anything more complicated than launching a single command from crontab may be better done by collecting the job in a separate script and instead schedule that script. This way, you can test and debug your script independently from cron, although since cron gives you a slightly different environment than your ordinary login shell environment, there are still environmental factors (like what the current working directory is and what the values of $PATH and other variables etc. are) to keep in mind.

Kusalananda
  • 333,661
  • Thank you for confirming this! – BenMorel Dec 03 '19 at 10:27
  • 2
    I learned through hard experience that putting your commands in a script, and just putting your script name into crontab, will save you hours of grief. In particular, cron may not be running the shell you think it is: a separate script can use a shebang to enforce a specific shell, it can log stuff, it can be tested independently. – Paul_Pedant Dec 05 '19 at 01:02
  • 2
    Have to agree with @Paul_Pedant . Already lost an hour or two to debug the usage of date +%Y%m%d in crontab. Hint: % has special meaning. – meolic Nov 26 '20 at 18:31