I want to automate a backup using dd in a bash script.

I currently use this command to create a backup image of my sda2 partition:

sudo dd bs=64K if=/dev/sda2 | gzip > /mnt/backup/backup_sda2_**TODAY**.img.gz 

I want to parameterise a bash script with a variable TODAY- where TODAY is the current DAY OF THE MONTH – so, for example 4th April 2021 will be 4

So my questions are:

1.How do I create the variable TODAY using system date?

2.How do I build it into the dd command above?

Many thanks


Use date +FORMAT to get the current day (FORMAT would be %d in your case) and command substitution ($(...)) to build it into your command:

sudo dd bs=64K if=/dev/sda2 | gzip > /mnt/backup/backup_sda2_$(date +%d).img.gz 

Note, that %d is zero-padded:

%d - day of month (e.g., 01)

Note, that this will backup the whole sda2 partition including empty space. There are surely better options, e.g. Ubuntu's Déjà Dup tool (a.k.a. "Backups"), which is doing incremental backups.

  • 2
    grrrrrrrrrrrrrrrr :D – Rinzwind Apr 14 at 10:48
  • Note that %d is zero-padded by default - if they really want "4th April 2021 will be 4" they'd need +%-d (although I don't recommend it - since it will make sorting of the generated files more difficult) – steeldriver Apr 14 at 11:13
  • true, thanks, added a hint ;-) I only tested with 14^^ – pLumo Apr 14 at 11:18
  • thanks for the suggestions. One question on dd- I normally do this via a live usb of ubuntu. But can I use the script above in a bash file on my actual system. I am new to Linux but I am guessing this means the partition I want to backup (sda2) is still mounted? – atombird Apr 14 at 12:37
  • Better to use rsync, not dd askubuntu.com/questions/1331348/… & askubuntu.com/questions/545655/… & askubuntu.com/questions/40992/… Ubuntu is relatively easy to reinstall, so better to plan that & backup your /home & data, list of installed apps and maybe /etc. – oldfred Apr 14 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.