user6238251 user6238251 - 3 months ago 8
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

Answer

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
  # ...
done

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:

#!/bin/bash

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

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