user6238251 user6238251 - 9 months ago 42
Bash Question

Shell script to loop and delete

Could someone help me on this.I have below folder structure as shown below .I want to loop through every folder inside the backuptest and delete all the folders except today date folder.i want it run as a cron job

enter image description here


You can get today's date in whatever format you require via the date command. For example,

TODAY=$(date +%Y-%m-%d)

You can loop over the subfolders you want with a simple wildcard match:

for d in /path/to/backuptest/*/*; do
  # ...

You can strip the directory portion from a file name with the basename command:

name=$(basename path/to/file)

You can glue that together something like this:


TODAY=$(date +%Y-%m-%d)

for d in /path/to/backuptest/*/*; do
  test "$(basename "$d")" = "$TODAY" || rm -rf "$d"