At the moment the size is nearly 30.0.GB but we know the whole OpenWrt in only a few MB in size. So how can I modify the code to only back up the OpenWrt partitions?
Then in luci goto system > attended sysupgrade. Press search firmware image. press request firmware image. It'll generate an image then there's an option to download image. This will contain all the packages you currently have installed.
If you have this and the tar backup, you'll be able to restore your system.
You can check which files will be backed up by going to system > Backup / Flash Firmware > configuration > open list. If you see files that aren't backed up, you can add them in the text box on the configuration page.
I'm not endorsing the idea of using dd at the block/device level for back-up purposes, but to answer your question based on info from post Losetup not working - #9 by Nightwalker83 where that last block allocated in the partition table is 509951 and from dd --help, you could look into using the count=N argument to dd where N is the last block allocated + 1 (or larger).
I think it might need + 1 since I think the first block is likely 0 and not 1.
You may also need to change the bs=20M parameter if that gets used with the count parameter.
To help this to be accurate in the future, you may want to automate the identification of the count value in case future installations or upgrades changes the partitions.
Something like the following might be worth testing:
There are several methods of generating a list of installed packages (user installed and/or pre-installed on the image) so that you don't have to keep track of them yourself and re-installation can be very simple. Beyond that, though, all of the basic configuration files are included in the backup that is generated by the sysupgrade backup routines (i.e. clicking the backup button in the web interface, or using the CLI equivalent). You can specify additional files/paths to backup as well, and those get included in the tarball.
As has been stated already, creating a bit-for-bit dd copy of your installation is not recommended. In some cases, it can get you back to where you were should you have a storage failure (on a traditional hard drive or SSD, or a flash card), but this can likely cause larger failures if the media itself contains any errors (in particular, never do this for embedded storage). And more importantly, this will only be useful to get you back to the exact version of OpenWrt, and doesn't provide any useful methods of upgrading to new versions since the files are not 'restorable' or even easily readable in this raw state.
Yes, provided you direct sysupgrade to include it. ie. my special files to backup:
Summary
## This file contains files and directories that should
## be preserved during an upgrade.
#/etc/example
/etc/openvpn/
/usr/sbin/netifd-netinfo.sh
/www/luci-static/resources/view/status/syslog.js
/root/.config/htop/htoprc
/root/.msmtprc