备份目录+使用bash重命名

时间:2012-09-12 08:44:24

标签: bash shell backup rename

我想通过将文件夹及其内容的副本放入与正在备份的文件夹相同的目录中的文件夹来备份文件夹及其内容。在备份目录中重新创建文件夹时,我想将下一个数字附加到文件夹名称。 例如:

MainDirectory目录:FolderImportant FolderBackup FolderOthers

FolderImportant永远不会是一个不同的名字。 FolderImportant及其内容需要复制到FolderBackup中,并在文件夹名称后附加编号001(在第一次备份时),内容保持不变。

我查看了论坛,发现了几个备份和重命名的例子,但是我知道关于bash的一点点我不知道怎么把所有东西都放到一体化的脚本中。

3 个答案:

答案 0 :(得分:0)

看看rsync,它是一个功能强大的工具,可以使用不同的策略进行备份。有些例子,请查看here

答案 1 :(得分:0)

rsync很棒......这是我对你的重击问题的回答

#!/bin/bash

dirToBackup=PATH_TO_DIR_TO_BACKUP

backupDest=BACKUP_DIR

pureDirName=${dirToBackup##*/}

for elem in $(seq 0 1000)
do
    newDirName=${backupDest}/${pureDirName}_${elem}
    if ! [ -d $newDirName ]
    then        
        cp -r $dirToBackup $newDirName
        exit 0
    fi
done    

答案 2 :(得分:0)

在bash的速成课程之后,我有一个功能脚本。请评论是否有可以改进此脚本的内容,因为我在学习bash脚本时不到6小时。

#! /bin/bash

# The name of the folder the current backup will go into
backupFolderBaseName="ImportantFolder_"
# The number of the backup to be appended to the folder name
backupFolderNumber=0
# The destination the new backup folders will be placed in
destinationDirectory="/home/$LOGNAME/.hiddenFolder/projectFolder/backupFolder"
# The directory to be backed up by this script
sourceDirectory="/home/$LOGNAME/.hiddenFolder/projectFolder/ImportantFolder"

# backupDirectory()-------------------------------------------------------------------------------------
# Update folder number and copy source directory to destination directory
backupDirectory() {
cp -r $sourceDirectory "$destinationDirectory/$backupFolderBaseName`printf "%03d" $backupFolderNumber`"
echo "Backup complete."
} #End backupDirectory()--------------------------------------------------------------------------------

# Script begins here------------------------------------------------------------------------------------
if ! [ -d "$destinationDirectory" ];
then
    echo "Creating directory"
    mkdir "$destinationDirectory"
    if [ -d "$destinationDirectory" ];
    then
        echo "Backup directory created successfully, continuing backup process..."
        backupDirectory
    else
        echo "Failed to create directory"
    fi
else
echo "Existing backup directory found, continuing backup process..."
for currentFile in $destinationDirectory/*
    do
        tempNumber=$(echo $currentFile | tr -cd '[[:digit:]]' | sed -e 's/^0\{1,2\}//')
        if [ "$tempNumber" -gt "$backupFolderNumber" ];
        then
            backupFolderNumber=$tempNumber
        fi
    done
    let backupFolderNumber+=1
backupDirectory
fi #End Script here-------------------------------------------------------------------------------------