Provided that you're using TWRP with version 2.1 (might work for higher versions too) and your data partition is not encrypted, you can make good use of OpenRecoveryScript.
The concept: When booted into recovery mode TWRP looks for a file named openrecoveryscript under the location /cache/recovery/. If the file is found, it is read and the instructions therewith executed accordingly. Once all the instructions are finished executing, the device reboots normally. All of this happens automatically the moment TWRP is fired up.
The important steps to make an automatic nandroid backup using TWRP are:
- Create the file openrecoveryscript under /cache/recovery. You would need root access to write into that location.
- Write into that file the instructions you want TWRP to execute. In my case I write:
backup SDCBM WeeklyBackup
You can understand the details about the command here. In short, I'm simply backing up System(S), Data(D), Cache(C), Boot(B) without creating MD5sums(M) and saving the backup with the name WeeklyBackup. The backup would automatically be saved under /sdcard/TWRP/BACKUPS/<device_serial>.
Afterwards, I set the appropriate permission on that script using the command:
chmod 664 /cache/recovery/openrecoveryscript;
Here's what I use to make an automatic backup in my Nexus 6:
- I found an automation app which allows editing a file, copying a file to directories with privileged access, or provides command-line access with superuser/root privileges. (I personally use Tasker, but MacroDroid and Automate may also work.)
- I created a day based profile in conjunction with a time based profile to trigger the backup on a certain day of the week/month and at a specific time.
Related: How to create a profile with multiple context in Tasker?
3. I added a task in that profile with following actions:
Code → Run Shell:
echo backup SDCBM WeeklyBackup > /cache/recovery/openrecoveryscript;
chmod 664 /cache/recovery/openrecoveryscript;
The first command would create the file openrecoveryscript and write the backup instruction in it.
* tick Use Root.
- System → Reboot → Type: Recovery.
The profile and task is very flexible, so you can make it more convenient to you, such as by pushing a notification or a toast with a time wait action at the beginning that the system would now make backup, so you should save your work or stop doing any important task and more...