0

I am currently using the following code:

#!/bin/bash

rm /media/external/archive/auth-settings.tar.raw
rm /media/external/archive/bak-settings.tar.raw
rm /media/external/archive/cont-settings.tar.raw
rm /media/external/archive/data-data.tar.raw
rm /media/external/archive/data-settings.tar.raw
rm /media/external/archive/mon-data.tar.raw
rm /media/external/archive/mon-settings.tar.raw
rm /media/external/archive/mail-data.tar.raw
rm /media/external/archive/mail-settings.tar.raw
rm /media/external/archive/portal-settings.tar.raw
rm /media/external/archive/webserver-data.tar.raw
rm /media/external/archive/webserver-settings.tar.raw

for f in /media/external/archive/*.tar.raw;
        do mv "$f" "${f%.*.tar.raw}.tar.raw";
done

to remove old backups once the new ones have been archived. However if for some reason the archiving fails, this script will be run regardlessly and it will remove all the archives, leaving nothing behind.

How can I modify the script in a way so that the rm command are only done if the the corresponding archive exists with a count number in its file name skipping the deletion if the numbered archive does not exist. For example:

auth-setting.tar.raw

should be removed only if there is a

auth-settings.number.tar.raw

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • you can use regular expressions in an if statement. in your case the regex is something like "[0-9].*" see: https://stackoverflow.com/questions/2348379/use-regular-expression-in-if-condition-in-bash also you should use an array for the filenames, saving you the copy-past work (which increases with the if conditon around the rm) – weberik Dec 11 '19 at 13:34

2 Answers2

0

You can use an if statement in the script. For example :

if [ -e auth-settings.*.tar.raw ]
then
    rm /media/external/archive/auth-settings.tar.raw
fi

the "*" characther give you a wildcard to insert between the 2 dots.

In this way you delete /media/external/archive/auth-settings.tar.raw only if "auth-settings.number.tar.raw" exist.

Zig Razor
  • 3,381
  • 2
  • 15
  • 35
  • This will not work if there's more than one matching file. See [this question](https://stackoverflow.com/questions/24615535/bash-check-if-file-exists-with-double-bracket-test-and-wildcards). – Gordon Davisson Dec 11 '19 at 16:02
0

This will return a list of files which have a number as in the format you provided, but it will strip the number so you can only delete this output :

find /media/external/archive/ -type f -regextype sed -regex ".*\.[0-9]\+\.tar\.raw" -print0 | xargs --null -L 1 basename | sed -E "s/(.*)(\.[0-9]+)(.*)/\1\3/g" 

Files in the directory :

 more-files.03242.tar.raw   
 somethingwithdot.3.tar.raw
 'with spaces.09434.tar.raw'

Output :

somethingwithdot.tar.raw
more-files.tar.raw
with spaces.tar.raw

Now you can safely iterate and delete these files as you can be sure they have a backup.

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49