🐧 How to Run Multiple Commands in One Cron Job – IT is good

🐧 How to Run Multiple Commands in One Cron Job – IT is good

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.

crontab -e 

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.

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.

#Run #Multiple #Commands #Cron #Job #good

Leave a Comment

Your email address will not be published. Required fields are marked *