On my new Ubuntu system I tried to start a Bash script automatically on system start up.
I found a lot of posts and how-to's about it.
so I tried to make it via Crontab:
- run
crontab -e
- add
@reboot /cronjobs/demo.sh >> /cronjobs/cronLogs/demo.output
- set execution permission to script with
sudo chmod +x /cronjobs/demo.sh
- reboot system
The output was created, but the script will not execute.
So I tried another solution with rc.local
file:
- run
sudo vi /etc/rc.local
- added
/cronjobs/demo.sh || exit 1
- reboot system
But my script doesn't run.
So I read that for reboot the script must be in /etc/rc0.d/
. So I tried this:
- move the script with
mv /cronjobs/demo.sh /etc/rc0.d/K99_demo.sh
- check permissions (all seems to be ok)
- reboot system
Same thing – script will not be executed.
So, what's my error? Why my script can't be executed?
I can execute my script if I run ./demo.sh
after i switched to the folder with cd /cronjobs
. The script is a demo-file which simply creates a folder:
#!/bin/sh echo demo output mkdir /cronjobs/demofolder
Edited: Replaced paths and filenames; added full content of demo.sh
file
Best Answer
The easiest solution is using sudo powers create a file like this in
/etc/cron.d/
:This avoids the use of a script file altogether and works for all users regardless of their home directory name, ie /home/steve, /home/mary, etc.
Edit - Add
sleep 10
For whatever reason cron is working too fast, or kernel is working too slow when making directories. An extra line
sleep 10
was necessary between the twomkdir
lines.You may not need 10 seconds in between the two make directory commands but 10 works on my system with an SSD.
Edit 2 - Make full directory path in one command
As per comments below a simpler method is to use:
-p
(long version--parents
) tellsmkdir
to automatically create all directory parent levels if they don't exist.-v
(long version--verbose
) tellsmkdir
to print the names of all directories created.