The following bash
script fragment would use the list of positional parameters (see further down for a variant that uses a named array instead) to store all the pathnames of old backups. When the new backup has been created, here simulated using touch
, the remembered old backups are deleted.
# Set backup dir variable and name of the new backup file.
backup_dir=/backups
printf -v backup_name 'backup_%(%Y_%m_%d_%H_%M_%S)T.txt' -1
Remember any old backups.
shopt -s nullglob # expand globs to nothing if no match
set -- "$backup_dir"/backup_????????????_??.txt
Debugging output.
if [ "$#" -gt 0 ]; then
printf 'Old file: %s\n' "$@"
else
echo 'No old files'
fi
Create the new backup at "$backup_dir/$backup_name".
Terminate if not successful.
touch "$backup_dir/$backup_name" || exit
Remove old files if there were any.
rm -f "$@"
Using a named array to hold the old backup files rather than the list of positional parameters. The code is identical, except for the assignment to oldfiles
and the expansions used with rm
and for producing the debugging output.
# Set backup dir variable and name of the new backup file.
backup_dir=/backups
printf -v backup_name 'backup_%(%Y_%m_%d_%H_%M_%S)T.txt' -1
Remember any old backups.
shopt -s nullglob # expand globs to nothing if no match
oldfiles=( "$backup_dir"/backup_????????????_??.txt )
Debugging output.
if [ "${#oldfiles[@]}" -gt 0 ]; then
printf 'Old file: %s\n' "${oldfiles[@]}"
else
echo 'No old files'
fi
Create the new backup at "$backup_dir/$backup_name".
Terminate if not successful.
touch "$backup_dir/$backup_name" || exit
Remove old files if there were any.
rm -f "${oldfiles[@]}"
Instead of terminating the script if the new backup isn't created successfully, we could instead do the removal of the old files in an if
statement, for example,
# Create the new backup.
# Remove old files if successful.
if touch "$backup_dir/$backup_file"
then
rm -f "$@" # or "${oldfiles[@]}" if you used the array and like typing longer things
fi