Crontab is a utility for running scheduled tasks at regular intervals on Unix-Linux systems.
It allows you to schedule multiple cron jobs to run at the same time.
We can schedule any shell command to be executed on the terminal.
Each scheduled task in crontab is separated by a new line.
We can also set multiple commands or scripts in a single cron job so that they run one after the other.
How to split two commands on Linux
You can separate two or more commands with a semicolon (;), logical AND operators (&&), or logical OR (||).
Which of these operators we use depends entirely on the requirements.
The following is a basic understanding of the use of these operators.
Semicolon (;): Used to separate multiple commands.
This executes all commands without checking the exit status of previous commands.
command_1; command_2; command_n
Logical operator AND(&&): used to separate commands when we only want to execute the next command if the previous command was successfully executed with an exit status of 0.
command_1 && command_2 && command_n
Logical OR operator (||): used to separate commands when we only want to execute the next command 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 you want to run the cron job as.
Then open the crontab editor by running the following command.
We then add a cron job entry to the file as shown below:
Executing Multiple Commands in One Cron Job
Let’s discuss real world examples of running multiple commands with crontab with different -2 delimiters.
Using a semicolon (;)
A semicolon can be used to separate two or more commands that do not require checking the exit status of the previous command.
For example, you need to change the permission of all files to 755, but you need to set 777 for the log directory.
0 2 * * * chmod –R 755 /was/www/myapp; chmod –R 777 /was/www/myapp/logs
Using the logical AND operator (&&)
Use this statement when you want to run the next command only if the previous one succeeded (exit status 0).
For example, you want to run backup.sh after successfully changing to the /backup directory.
0 2 * * * cd /backup && bash backup.sh
Using the logical operator OR (||)
Use the logical OR operator (||) when you want to execute the next command only if the previous one fails (exit status is not 0).
For example, you want to show a message or send an email if the backup file is not found
0 2 * * * [ –f /backup/mydb–`date +%F`.sql ] || echo “Today’s backup file not found”
In this blog post, you learned about running multiple commands in a single cron job entry.
Various options for separating teams were also considered.
This article provides basic information about each delimiter that is used to separate commands.
#Run #Multiple #Commands #Cron #Job #good