结合getfattr进行Bash脚本比较



我目前在Bash脚本中遇到了一个问题,每次试图修复它时,我似乎都会在黑暗中运行得更深。

背景:我们有一个文件夹,里面充满了编号的崩溃文件夹,里面装满了崩溃文件。有人每天都在导出这些文件夹的列表。在导出过程中,编号的崩溃文件夹会得到一个属性"user.exported=1"。

其中一些不会被导出,因此它们将不具有该属性,并且只有在它们超过30天时才应删除这些属性。

我的问题:我正在设置一个bash脚本,该脚本最终通过Cron运行,以定期检查文件夹,这些文件夹具有"user.exported=1"属性,并且超过14天,并通过rm -rfv FOLDER >> deleted.log删除它们

然而,我们也有一些文件夹没有或没有"user.exported=1"属性,这些文件夹在超过30天后需要删除。我创建了一个IF ELIF FI比较来检查这一点,但这就是我陷入困境的地方。

我的代码:

#!/bin/bash
# Variable definition
LOGFILE="/home/crash/deleted.log"
DATE=`date '+%d/%m/%Y'`
TIME=`date '+%T'`
FIND=`find /home/crash -maxdepth 1 -mindepth 1 -type d`
# Code execution
printf "n$DATE-$TIMEn" >> "$LOGFILE"
for d in $FIND; do
# Check if crash folders are older than 14 days and have been exported
if [[ "$(( $(date +"%s") - $(stat -c "%Y" $d) ))" -gt "1209600" ]] && [[ "$(getfattr -d --absolute-names -n user.exported --only-values $d)" == "1" ]]; then
#echo "$d is older than 14 days and exported"
"rm -rfv $d" >> "$LOGFILE"
# Check if crash folders are older than 30 days and delete regardless
elif [[ "$(( $(date +"%s") - $(stat -c "%Y" $d) ))" -gt "1814400" ]] && [[ "$(getfattr -d --absolute-names -n user.exported $d)" == FALSE ]]; then
#echo "$d is older than 30 days"
"rm -rfv $d" >> "$LOGFILE"
fi
done

IF部分运行良好,它删除了属性为"user.exported=1"的文件夹,但ELIF部分似乎不起作用,因为我在bash中只得到一个输出,例如:

/home/crash/1234: user.exported: No such attribut
./crash_remove.sh: Line 20: rm -rfv /home/crash/1234: File or Directory not found

当我在脚本运行后查看崩溃文件夹时,文件夹及其内容仍然存在。

我的剧本肯定有错误,但看不见。请有人帮我解决这个问题吗?

提前感谢

只引用展开式,而不是整个命令。

代替:

"rm -rfv $d"

do:

rm -rfv "$d"

如果引用所有内容,bash将尝试运行一个名为rm<space>-rfv<space><expansion of d>的命令。

不要使用回溯标记`。请改用$(...)。Bash黑客wiki过时的弃用语法。

不要使用for i in $(cat)var=$(...); for i in $var。使用while IFS= read -r循环。如何在bash中逐行读取文件。

不使用if [[ "$(( $(date +"%s") - $(stat -c "%Y" $d) ))" -gt "1814400" ]],只需在算术扩展中进行比较,如:if (( ( $(date +"%s") - $(stat -c "%Y" $d) ) > 1814400 ))

我认为你可以在find中完成所有操作,比如:

find /home/crash -maxdepth 1 -mindepth 1 -type d '(' 
-mtime 14 
-exec sh -c '[ "$(getfattr -d --absolute-names -n user.exported --only-values "$1")" = "1" ]' -- {} ; 
-exec echo rm -vrf {} + 
')' -o '(' 
-mtime 30 
-exec sh -c '[ "$(getfattr -d --absolute-names -n user.exported "$1")" = FALSE ]' -- {} ; 
-exec echo rm -vrf {} + 
')' >> "$LOGFILE"