Shell script for cron job

cronshellshell-script

I've just set-up one cron-job in cpanel, but although it seems to be executing the script it doesn't work as intended.

Here is the cron job command in cpanel:

/bin/sh /home/my-username/cronjobs/sedclearmalw.sh

and here is the content of the script :

#!/bin/bash
cd ../public_html/
grep -rl '_0xaae8' . | xargs sed -i 's/var\s_0xaae8.*//g'

I believe the cd command should be correct, as it needs to go back a directory and then enter public_html, however the second command seems to be the problem.
I have tried running it via ssh, (bash sedclearmalw.sh) it seems like it's running for ~15 seconds but it's not doing its job , as i checked with the following command :

grep -rl '_0xaae8'

and it returns 1 file containing _0xaae8.
Any help will be appreciated, it must be something simple as i know the above command in the shell script works all right when executed via ssh (not through the script).

Best Answer

The problems is due to the use of a relative path. When cron runs a scheduled job, it uses the home directory of the owner as its working directory, e.g., if I schedule a job as the root user, its working directory will be /root/ (on a Cent OS system).

You should specify the absolute path in your cd command. If you’re not running any further commands in your script, you could just run it all in one line:

grep -rl '_0xaae8' /full/path/to/public_html/ | xargs sed -i 's/var\s_0xaae8.*//g'
Related Question