4

I'm new to crontab and would like to run the following script from /etc/crontab:

0 15    * * *   root    bash-c 'for i in /home/dell/Downloads/*.{pdf,docx,png,jpg,PDF,DOCX}; do shred -zvu "$i" -n20; done'

I have tried with and without bash-c option, yet the script doesn't run.

My objective is:

  1. Get this script running from Crontab
  2. Get this script running on startup

Help is appreciated.

dessert
  • 39,982
orrp
  • 43
  • 2
    Consider putting this in your user crontab (i.e. crontab -e as user dell) instead of in the system crontab as root. – marcelm Feb 27 '19 at 14:09
  • Thanks for all comments. Executing the command in a script and adding this all to crontab -e, instead of trying to modify /etc/crontab seems to resolve the issues. One question remains: Running -> 31 15 * * * /home/dell/shred.sh -> works. Running -> @reboot /home/dell/shred.sh -> does not work. One of my main frustrations here is that there are no error messages, no indication what is done incorrectly. Appreciate your input how I can run this script on startup. – orrp Mar 02 '19 at 13:40

1 Answers1

13

You're missing a space after the command bash and the argument -c.

This should work:

0 15    * * *  root bash -c 'for i in /home/dell/Downloads/*.{pdf,docx,png,jpg,PDF,DOCX}; do shred -zvu "$i" -n20; done'

Some additional hints:

  • Don't run a crontab as user root if you don't need to.
  • You wrote that you put it in /etc/crontab file. Don't edit crontab files directly, rather use crontab -e command or sudo crontab -e for commands which need root rights. Note, that you don't put the user field in the "other" crontab files.
  • If you have more than one command you can use bash -c as you do, but I'd rather put the commands in a script and execute this from crontab.

  • To run a script on startup, you can use @reboot instead of 0 15 * * *.

pLumo
  • 26,947
  • 5
    “I'm not sure what the word root is about here.” See the header of /etc/crontab: Unlike any other crontab you don't have to run the crontab command to install the new version when you edit this file and files in /etc/cron.d. These files also have username fields, that none of the other crontabs do. However, in this case, only the user’s home folder is involved, so root should be not used in this case. – Melebius Feb 27 '19 at 08:30
  • 1
    thanks, as I never edited /etc/crontab directly I didn't even know this... :-D – pLumo Feb 27 '19 at 08:32
  • 2
  • 1
    I suspect there may be a more fundamental issue with running a bash -c command from cron, since IIRC each command is implicitly executed by /bin/sh -c (or, more exactly, $SHELL -c). It may be necessary to set SHELL=/bin/bash (to suport brace expansion etc.) and then run the command without the bash -c wrapper. But really the best approach (as you note) is to put the bash code in an external script file. – steeldriver Feb 27 '19 at 09:18