Linux
如何將目錄中的所有文件移動到另一個,但複製最新?
我正在嘗試編寫一個備份腳本,該腳本從目錄中移動所有文件,但只複製最新修改/最新的文件。
我遇到了一些麻煩,我無法返回正確的最新文件,因為我認為我無法通過修改獲取
find
或ls
列出文件,並且只輸出文件名。所以我$latestfile
最終成為一個不同的文件。幫助?
我目前的程式碼:
# Primary Backup Location BACKUP_LOCATION=/my/backup/dir # List latest file latestfile=$(find ${BACKUP_LOCATION} -maxdepth 1 -mindepth 1 -type f -exec basename {} \; | sort -nr | awk "NR==1,NR==1 {print $2}") echo "Latest file is $latestfile" # List all (EXCEPT LAST) files and get ready to Backup echo "Backing up all files except last" for file in $(find ${BACKUP_LOCATION} -maxdepth 1 -mindepth 1 -type f \! -name "$latestfile" -printf "%f\n" | sort -nr ) do echo $file #mv $file /some/target/dir/$file done
想出瞭如何使這項工作。這是我的備份腳本的一部分,希望有人會發現它有用。
# Location to Backup from BACKUP_TARGET="/my/dir/to/backup" # Location to Backup to BACKUP_LOCATION="/my/backup/store" # List latest file file_latest=$(find ${BACKUP_TARGET} -maxdepth 1 -mindepth 1 -printf '%T+ %p\n' | sort -r | head -n 1 | sed 's|.*/||' ) echo "Latest file is $file_latest" # List the rest of files file_rest_of_em=$(find ${BACKUP_TARGET} -maxdepth 1 -mindepth 1 -type f \! -name "$file_latest" | sed 's|.*/||' ) # make newlines the only separator IFS=$'\n' # Backup all previous Backups, MOVE ALL echo "Backing up all files except Latest Backup..." for file in $file_rest_of_em do echo "Moving $file" mv -n ${BACKUP_TARGET}/$file $BACKUP_LOCATION/ done # Backup Latest Backup, LEAVE COPY BEHIND if [ -f "$BACKUP_LOCATION/$file_latest" ]; then echo "$file_latest (Latest Backup) already exists." else echo "$file_latest (Latest Backup) does not exist." echo "Copying $file_latest..." cp -n --preserve=all ${BACKUP_TARGET}/$file_latest $BACKUP_LOCATION/ fi # done with newline shenanegans unset IFS
感謝您的幫助@Panki