Bash脚本遍历并比较循环中的文件日期

时间:2013-05-06 04:36:13

标签: bash file date loops compare

所以我想比较一个文件夹中文件的修改日期。我知道你可以将它与-nt或-ot进行比较,但我不知道如何遍历文件并进行比较。我知道你必须分配一个文件作为前一个文件,但我不知道它的代码。

例如,我有一个说3个文件的文件夹,a,b和c。在for循环中,我想比较一个(前一个条目)和b(条目)。如果a比b更新,则删除b。等等。

我正在试图找出如何分配“之前的条目”。

谢天谢地!

echo "Which directory would you like to clean?"
read directory
echo "Are you sure you want to delete old back ups? Y for yes"
read decision
if [ $decision = "y" ]
then
for entry in "$directory"/*

do
#need to somehow assign the previous entry and current entry to a variable
if [ $entry -nt $previousEntry ]
rm -i $previousEntry
echo "Deleted $previousEntry"
fi
done
echo "Deleted all old files"

else
echo "Exiting"
exit 1
fi

2 个答案:

答案 0 :(得分:0)

想出来。 2个嵌套的for循环。谢谢你。

echo "Which directory would you like to clean?"
read directory
echo "Are you sure you want to delete old back ups? Y for yes"
read decision
if [ $decision = "y" ]
then

# Beginning of outer loop.
for entry in "$directory"/*
do
  # Beginning of inner loop.
  for previousEntry in "$directory"/*

  do
if [[ $entry -nt $previousEntry ]] #nt = newer than
then
echo "$entry is newer than $previousEntry"
echo "Deleting $previousEntry"
rm -i $previousEntry
fi 
  done
  # End of inner loop.

done

fi #end first if

答案 1 :(得分:0)

在这里,我只是移动到该目录并删除除最新文件之外的所有文件。

echo "Which directory would you like to clean?"
read directory
echo "Are you sure you want to delete old back ups? Y for yes"
read decision
if [ $decision = "y" ]
then
cd $directory
ls -tr | head --lines=-1|xargs rm -f  ;
echo "Deleted all old files"

else
echo "Exiting"
exit 1
fi