Title: script not running via crontab
Tags: linux;bash;shell;cron
Question: I have created a shell script which deletes subfolder of var/cache folder. Please check below script.
#!/bin/sh
now=$(date +"%Y-%m-%d %T")
if rm -rf var/cache/* ; then
echo "$now: Deleted"
echo "$now: problem"
When I run this shell file directly by command sh hello.sh it works fine.
But when I run this file using crontab it creates an entry in log file but doesn't delete subfolder of var/cache/..
Please check my crontab as well.
*/1 * * * * /bin/sh /www/html/wp/hello.sh >> /www/html/var/log/redis.flush.cron.log 2>&amp;1
Please suggest how can I run that file using crontab.
Comment: @KaranAdhikari if you want to set a cron job for root which has access to all the folders then you can use the command `sudo crontab -e -u root`

Comment: The folders are not getting deleted due to permissions issue i guess, check the permissions of the file `ls -la`

Comment: does the folder has read-write permission? check if the user has permission to delete the folder and the command to delete should be `rm -rf /var/cache/`. Is the path correct?

Comment: what is the current working directory when running directly, also is there a reason not to put the entire path before `var/`

Comment: from [this answer](https://unix.stackexchange.com/a/38956/23266) cron runs command directly in the home directory of the user

Comment: @NullDev no i haven't added any user in crontab but if i want to run it from different user like abc then what would be the syntax for that

Comment: @RajanSharma i have created that crontab by logged in as abc user.. so i don't think it would be a permission issue. when i run this command sudo crontab -l -u abc .it given me value of that crontab..

Comment: @NahuelFouilleul wp is my current working directory when i run it directly..
is there a reason not to put the entire path before var/ : no it was working fine when i run it directly so i thought it would work with cron too.

Comment: @NahuelFouilleul it worked when i replaced var/cache/ to absolute path.. thanks for your help

Comment: Always use absolute paths


Here is another answer: Try using an absolute path instead of var/cache. When you run it via cron, it will run a) as a specific user, and b) from the home directory of that user. One or both of these might be causing issues for you.
Instead of this:
if rm -rf var/cache/* ; then
Try something like this:
if rm -rf /full/path/to/var/cache/* ; then

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 10, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2019:00:07/15/19', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<linux><bash><shell><cron>', 'Title': 'script not running via crontab', 'ViewCount': 137, 'id': 57039837, 'user_AboutMe': '', 'user_AccountId': 4985132.0, 'user_DisplayName': 'Karan Adhikari', 'user_Reputation': 485.0, 'user_Views': 117.0, 'user_id': 4008990.0}}