Issue
Main-agenda: I am trying to automate shutdown and restart of my computer using cron
. To be exact, I want to shutdown my computer at 10:30 pm and restart my computer at 06:00 am everyday.
Progress so far:
I can automate shutdown. (I don't even use
cron
. I just usesleep $duration; poweroff
. Andduration
is computed as target time minus current time).For automating restart I am following this askubuntu answer. I could successfully run the "Simple test to wake the machine 5 minutes from now". It works fine!
Now comes the part where I try to figure out: how to use
cron
. So I basically want to run something like this everyday:sudo sh -c "echo $(date +%s -d '+1 day 6:30') > /sys/class/rtc/rtc0/wakealarm"
(Remark: standalone, the above works fine).
So I try this:
sudo crontab -e
and added the following line there:*/1 * * * * echo "$(date +%s -d '+1 day 6:30')" > /sys/class/rtc/rtc0/wakealarm
Remark: I am using
*/1 * * * *
for testing purposes only. Finally when everything works I plan to use@reboot
.The above doesn't work. So I have tried looking online and debugging. From this unix.stackexchange answer I get the idea that "by default
cron
is usingsh
to run the task instead ofbash
". So I addedSHELL=/bin/bash
in thesudo crontab -e
file.Next I have broken the above
echo
into simpler things and now, I know some of them work and some of them don't.
Currently, the output of sudo crontab -l
is:
SHELL=/bin/bash
*/1 * * * * echo "$(date)" > /home/username/a.txt
*/1 * * * * echo "1659800001" > /sys/class/rtc/rtc0/wakealarm
*/1 * * * * echo "$(date +%s)" > /home/username/b.txt
*/1 * * * * echo "$(date +%s -d '+1 day 6:30')" > /sys/class/rtc/rtc0/wakealarm
Of these - the first 2 commands execute correctly! However the 3rd and 4th commands don't execute. 4th command is what I want to work.
So my guess is that $(date +%s)
is the problem? Please help me proceed from here!
Solution
Your intuition about the % is correct. See man 5 crontab
:
A "%" character in the command, unless escaped with a backslash (), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.
This will work with the % escaped:
*/1 * * * * echo "$(date +\%s -d '+1 day 6:30')" > /sys/class/rtc/rtc0/wakealarm
However, I wonder why you want to do the echo? This will also work:
*/1 * * * * date +\%s -d '+1 day 6:30' > /sys/class/rtc/rtc0/wakealarm
Answered By - EricH Answer Checked By - Katrina (WPSolving Volunteer)