I want to write a script which will create a single compressed-archive file consisting of the largest files above a certain threshold from multiple directories. For example, I would like to know how to take the 5 largest files above 2MB and put them into a compressed archive file called largestfile.tar.gz
. Here is what I have so far:
du -a $path | sort -n -r | head -n 5 > diskspacefile.txt
file=$(cat diskspacefile.txt)
while read p; do
filesize=echo $p | awk '{print $1 }'
if [ $filesize > 2000000 ]
then
zipfile=`echo $p | awk '{print $2 }'`
tar -zcvf largestfile.tar.gz $zipfile
fi
done
Unfortunately this does not appear to work. When I run it I either get only a single file in the archive or no files at all. For context, the directories I'm interested in applying this to are /root
and /boot
(i.e. these will be the values for the path
variable in the code snippet).
du -a $path | sort -n -r | head -n 5 > diskspacefile.txt file=$(cat diskspacefile.txt) while read p; do filesize=
echo $p | awk '{print $1 }'` if [ $filesize > 20000000 ] ; then zipfile=echo $p | awk '{print $2 }'
tar -zcvf largestfile.tar.gz $zipfile fi done < diskspacefile.txtdone
is missing.largestfile.tar.gz
. For every iteration, same file is getting overwritten.-r
option:-r, --append append files to the end of an archive
. Otherwise yourtar
command will create a new archive with only a single file in it each time.