To run crontab script with specific user

Hi Guys,

I am have made a below entry in crontab using root user and need to trigger the script every one hour using test user.
But the script is not getting triggered. Could anyone help
OS - Linux
Script - Bash

0 * * * * su test -c "/script_path/my_script.sh"

cron is a scheduler that is very basic in its understanding, see that as if you were talking to a true idiot, you have to give all information and details on what is required to do the job scheduled... As it has minimalist environement, if anything more is needed, it needs to be found in the script etc...

su test

opens a new shell also as test only the does not inherit of test's env when he connects interactively...
So to be basic best practice is to write jobs for cron and not give command line stuff, your job should be like

#!/usr/bin/ksh
#
# Set all needed variable
# Set needed environment

su test -c "/script_path/my_script.sh"
.
.
# exit

Now, why are you running this as root that su UID, rather than the desired UID ?

Hi,
Thanks for the inputs, Basically the crontab entry is only enabled for root users. I wanted to run my script using test user rather than as root. So is there a way to run as test user while scheduling from cron as root

Try to write the job as shown, and show us what it gives...
by default only root is configured to use cron but you can customise and enable other users... The same for at

Use the system-wide /etc/crontab that allows a user name to be specified.

How are you entering the cron job in the tables?? Are you using crontab command to enter the job or are you editing the crontab file directly? If you editing directly it's no surprise that it isn't being triggered because the cron daemon won't know about it (yet).

How to add the entry with this option ? can you help with my script

0 * * * * script_path/my_script.sh 

Try as given in example above

# m h dom mon dow user command
17 * * * * root run-parts --report /etc/cron.hourly

would yield

0 * * * * test /script_path/my_script.sh
1 Like

kindly add - to su like or sudo test
0 * * * * su - test -c "/script_path/my_script.sh"