简体   繁体   English

Shell脚本循环和删除

[英]Shell script to loop and delete

Could someone help me on this.I have below folder structure as shown below .I want to loop through every folder inside the backuptest and delete all the folders except today date folder.i want it run as a cron job 有人可以帮我这个忙。我有下面的文件夹结构,如下所示。我想遍历backuptest中的每个文件夹并删除除今天日期文件夹之外的所有文件夹。我希望它作为cron作业运行

在此处输入图片说明

Use find for this: 为此使用find

today="$(date +%Y-%m-%d)"
find /path/to/backuptest/Server* -mindepth 1 -maxdepth 1 -type d -not -name "$today" -exec rm -R {} \;

Edit 编辑

To not delete directories other than those containing a date structure, use something like 要不删除除包含日期结构的目录以外的目录,请使用类似

find /path/to/backuptest/Server* -mindepth 1 -maxdepth 1 -type d  -regex ".*2016-[0-1]*[0-9]-[0-3][0-9]$" -not -name "$today"

You can do it with find: 您可以使用find做到这一点:

set date=`date +%Y-%m-%d`
find backuptest -type d -not -name $date -not -name "backuptest" -not -name "Server*" -exec rm -rf {} \;

This: 这个:

find backuptest -type d -not -name $date -not -name "backuptest" -not -name "Server*"

will look for directories name different than: 将查找与以下名称不同的目录名称:

backuptest
Server*
$date -> current date

and remove them with: 并使用以下命令将其删除:

rm -rf 

You can get today's date in whatever format you require via the date command. 您可以通过date命令以所需的任何格式获取今天的日期。 For example, 例如,

TODAY=$(date +%Y-%m-%d)

You can loop over the subfolders you want with a simple wildcard match: 您可以使用简单的通配符匹配来遍历所需的子文件夹:

for d in /path/to/backuptest/*/*; do
  # ...
done

You can strip the directory portion from a file name with the basename command: 您可以使用basename命令从文件名中删除目录部分:

name=$(basename path/to/file)

You can glue that together something like this: 您可以将其粘合在一起,如下所示:

#!/bin/bash

TODAY=$(date +%Y-%m-%d)

for d in /path/to/backuptest/*/*; do
  test "$(basename "$d")" = "$TODAY" || rm -rf "$d"
done

Update: 更新:

If you don't actually want to purge all subfolders except today's, but rather only those matching some particular name pattern, then one way to accomplish that would be to insert that pattern into the glob in the for command. 如果您实际上不希望清除除今天的子文件夹以外的所有子文件夹,而只清除那些与某些特定名称模式匹配的子文件夹,那么一种完成该方法的方法是将该样式插入for命令的glob中。 For example, here 例如这里

for d in /path/to/backuptest/*/+([0-9])-+([0-9])-+([0-9]); do
  test "$(basename "$d")" = "$TODAY" || rm -rf "$d"
done

the only files / directories considered for deletion are those whose names consist of three nonempty, hyphen-separated strings of decimal digits. 唯一被考虑删除的文件/目录是名称由三个非空,连字符分隔的十进制数字组成的文件/目录。 One could write patterns that more precisely match date string format if one preferred, but it does get messier the more discriminating you want the pattern to be. 如果愿意的话,可以编写与日期字符串格式更精确匹配的模式,但是如果您希望该模式更具区分性,它的确会变得更加混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM