Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to pass arguments to shell script in crontab ?

  • Last Updated : 18 Jul, 2021

In this article, we will discuss how to schedule shell scripts in contrab and to pass necessary parameters as well.

First, let’s create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run.

#! /usr/bin/sh
SUM=0
for i in $@ 
do 
    SUM=`expr $SUM + $i`
done
echo "$SUM was calculated at `date`"

Note: #! /usr/bin/sh (specifying the path of script interpreter) is necessary if wish to make the script executable.

Assuming we have saved this script as  my_script.sh under our home directory, we can make it executable by entering the following command in our terminal:

chmod +x my_script.sh

We can test our script if it is working properly:



./my_script.sh 1 2 3 4 5
15 was calculated at Thursday 01 July 2021 01:24:04 IST 2021

The crontab scheduling expression has the following parts:

To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:

crontab -e

You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:

*/2 * * * * /home/$(USER)/my_script.sh 1 2 3 4 5 >> /home/$(USER)/output.txt

where $(USER) can be replaced with your username. Save changes and exit. This will schedule our shell script to run every 2 minutes with 1 2 3 4 5 as command-line arguments and write the output to /home/$(USER)/ouput.txt.

Note: There are a few things to keep in mind before scheduling cron jobs:

  • All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice.
  • All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them.
  • All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering.
My Personal Notes arrow_drop_up
Recommended Articles
Page :