Automate Daily Task with Bash and Cron

Here is a simple method in which I am automating the creation of “Tomorrow’s notes” for my Obsidian.md notes[1]. In a similar manner, any simple tasks that needs to be repetitively done daily can be done with the help of bash scripting and cron job.

image-20210620152537689

The above shows the daily notes I indent to create on a daily basis for the next day. This, I have implemented with the simple steps.

  1. Check if tomorrow’s file doesn’t exist (or if it exists, check if its empty) [ ! -s filename ]
  2. If the above statement is true, create an empty file of the filename and copy the predefined texts to it.

You may have noticed that my Date Format is a bit different. This can be achieved using the linux’s date command. This can be written as a bash script as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#! /bin/bash -e

HM="/home/username"
TODAY=$(date +%d-%m-%y-%A)
YDY=$(date +%d-%m-%y-%A --date=yesterday)
TMW=$(date +%d-%m-%y-%A --date=tomorrow)
DATMW=$(date +%d-%m-%y-%A --date="tomorrow tomorrow")
JNL="Documents/Notes/Journal"

if [ ! -s $HM/$JNL/$TMW.md ]
then
	touch $HM/$JNL/$TMW.md
	cat <<- EOF > $HM/$JNL/$TMW.md
	Date: [[$TMW]]
	Previous: [[$TODAY]]  
	Next: [[$DATMW]]

	## Agenda
	- 
	- 

	## Tasks
	- [ ] 

	## Today's Notes
	Readings:
	EOF
fi

The output of the cat command (which is the rest of the text until EOF) is piped to the file using a method called as Here document redirection. This can be extensively helpful in remote SSH sessions as well. Note that, you have to replace username with your respective username. (One can also use the $HOME variable if the service is initiated in user profile. I am not doing that). After creating, I had saved it with the filename create-daily.sh.

The next step is to make it a daily task which gets automatically executed everyday. The problem with cron is that it is meant server environment. Hence, if your computer resumes after a shutdown, it won’t get executed. The solution is to use anacron which Ubuntu happens to use by default. Hence, one can simply copy the above script to a predefined folder as follows

1
2
sudo cp create-daily.sh /etc/cron.daily/create-daily
sudo chmod +x /etc/cron.daily/create-daily

If you are using WSL inside windows, you have to run the following to create the file compatibility with bash. (I haven’t actually run an anacron job inside WSL. Hence, if any issue rises, please let me know)

1
2
sudo apt install anacron dos2unix
sudo dos2unix /etc/cron.daily/create-daily

Thus, such simple but time consuming jobs can be automated.


  1. Obsidian supports template for “Today’s notes” but it doesn’t support tomorrow’s notes yet. Hopefully, it may get implemented in a later release. 

Load Comments?