Bash - 使用循环使备份脚本更高效

Bash - 使用循环使备份脚本更高效

我有一个备份脚本(bash)。下面显示了其中的一部分。此脚本每 14 天轮换一次备份。如果我想将其更改为 30 天,我必须写出 30 个这样的 if-then 块。我确信这可以用一个漂亮的 for 循环来代替。它会是什么?

# step 1: delete the oldest snapshot, if it exists:
if [ -d $BACKUP_DIR/daily.14 ] ; then                   \
$RM -rf $BACKUP_DIR/daily.14 ;                          \
fi ;

# step 2: shift the middle snapshot(s) back by one, if they exist
if [ -d $BACKUP_DIR/daily.13 ] ; then                   \
$MV $BACKUP_DIR/daily.13 $BACKUP_DIR/daily.14 ; \
fi;

if [ -d $BACKUP_DIR/daily.12 ] ; then                   \
$MV $BACKUP_DIR/daily.12 $BACKUP_DIR/daily.13 ; \
fi;

if [ -d $BACKUP_DIR/daily.11 ] ; then                   \
$MV $BACKUP_DIR/daily.11 $BACKUP_DIR/daily.12 ; \
fi;

if [ -d $BACKUP_DIR/daily.10 ] ; then                   \
$MV $BACKUP_DIR/daily.10 $BACKUP_DIR/daily.11 ; \
fi;

if [ -d $BACKUP_DIR/daily.9 ] ; then                    \
$MV $BACKUP_DIR/daily.9 $BACKUP_DIR/daily.10 ;  \
fi;

if [ -d $BACKUP_DIR/daily.8 ] ; then                    \
$MV $BACKUP_DIR/daily.8 $BACKUP_DIR/daily.9 ;   \
fi;

if [ -d $BACKUP_DIR/daily.7 ] ; then                    \
$MV $BACKUP_DIR/daily.7 $BACKUP_DIR/daily.8 ;   \
fi;

if [ -d $BACKUP_DIR/daily.6 ] ; then                    \
$MV $BACKUP_DIR/daily.6 $BACKUP_DIR/daily.7 ;   \
fi;

if [ -d $BACKUP_DIR/daily.5 ] ; then                    \
$MV $BACKUP_DIR/daily.5 $BACKUP_DIR/daily.6 ;   \
fi;

if [ -d $BACKUP_DIR/daily.4 ] ; then                    \
$MV $BACKUP_DIR/daily.4 $BACKUP_DIR/daily.5 ;   \
fi;

if [ -d $BACKUP_DIR/daily.3 ] ; then                    \
$MV $BACKUP_DIR/daily.3 $BACKUP_DIR/daily.4 ;   \
fi;

if [ -d $BACKUP_DIR/daily.2 ] ; then                    \
$MV $BACKUP_DIR/daily.2 $BACKUP_DIR/daily.3 ;   \
fi;

if [ -d $BACKUP_DIR/daily.1 ] ; then                    \
$MV $BACKUP_DIR/daily.1 $BACKUP_DIR/daily.2 ;   \
fi;


# step 3: make a hard-link-only (except for dirs) copy of the latest snapshot, if that exists
if [ -d $BACKUP_DIR/daily.0 ] ; then                    \
$CP -al $BACKUP_DIR/daily.0 $BACKUP_DIR/daily.1 ;       \
fi;

答案1

#!/bin/bash
MAX=29

for i in `seq 1 $MAX` 
do 
    echo " check file exists directory.$i"
    echo "mv directory.$i to directory" `expr $i - 1`
done

这可能是一个很好的起点

答案2

for i in {7..1};
do
        #echo "$i"

        if [ -d $BACKUP_DIR/daily.${i} ]
        then
                z=$(($i+1));
                #echo "$z"
                echo "moving daily.$i to daily.$z"
                $MV $BACKUP_DIR/daily.$i $BACKUP_DIR/daily.$z ;
        fi;
done

相关内容