Linux

How to Run Multiple Commands in Single Cron Job

Tags:
Share on:

Table of Contents

Crontab stands for “cron table”. It allows to use job scheduler, which is known as cron to execute tasks. Crontab is also the name of the program, which is used to edit that schedule. It is driven by a crontab file, a config file that indicates shell commands to run periodically for the specific schedule.

How to Sepreate Two Commands in Linux

You can separate two or more commands by using semicolons (;), logical AND (&&), or logical OR (||) operators. Which of these operators we use, is totally depends on the requirements. Here is the basic understanding of using these operators.

  1. Semicolon (;): is used to separate multiple commands. This executes all the commands without checking the exit status of previous commands.
    command_1;  command_2;  command_n
    
  2. Logical AND (&&): is used to separate commands when we want to execute the next command only if the previous command was successfully executed with exit status 0.
    command_1 &&  command_2 &&  command_n
    
  3. Logical OR (||): is used to separate commands when we want to execute the next command only if the previous command failed with a non-0 exit status.
    command_1 ||  command_2 ||  command_n
    

How to Schedule a Cron Job

First, switch to the user from which you want to run a cron job. Then open the crontab editor by running the following command.

crontab -e 

Then you add a cron job entry to the file like below:

Logical OR separated commands in Linux

Crontab commands separated with logical AND

Running Multiple Commands in Single Cron Job.

We can separate two or more commands with semicolons, that don’t require checking the exit status of the previous command. For example, you need to change the permission of all files to 777 but need to set 777 for the logs directory.

0 2 * * *   chmod -R 755 /var/www/myapp; chmod -R 777 /var/www/myapp/logs

 

Semicolon (;) separated commands in Linux

Crontab commands separated with semicolon (;)

Use this operator, where you want to run the next command only if the previous is executed successfully (exit status 0). For example, you want to run the backup.sh after successfully changing to /backup directory.

0 2 * * *   cd /backup && bash backup.sh

Logical OR separated commands in Linux

Crontab commands separated with logical AND

Use the logical OR (||) operator, when you want to run the next command only if the previous is failed (exit status non-0). For example, you want to show a message or send an email if the backup file not found.

0 2 * * *  [ -f /backup/mydb-`date +%F`.sql ] || echo "Today's backup file not found"

 

Logical AND separated commands in Linux

Crontab commands seperated with logical AND

    • Using Semicolon (;)
    • Using Logical AND (&&)
    • Using Logical OR (||)