zipping files then remove the folders

Hi,

i am using the below script to zip the files with respect to their timestamp of the files.It is working fine.

For example lets take I have two files in this directory /path/folder1 with the timestamp as this month and previous month. When i run this script first time it is creating two folders under this directory path

path/folder1/oct_bkp_files
path/folder1/sep_bkp_files

also getting the zipped folders of these respectively.

when i un the script second time, again the zipped file

sep_bkp_files.zip is getting zip and and adding with the oct_bkp_files.zip folder.

If no files exixts in path/folder1 then it should come out and should not do anything.

i.e) If there is no files in path/folder1 directory then it should return "No Files exists to backup".

cd /path/folder1
if [ -f *.* ]; then
ls -lrt | awk -v '/^\-/{print $6,$NF}' | while read month filename
do
mkdir -p /path/folder1/${month}_bkp_files
mv ${filename} /path/folder1/${month}_bkp_files
zip -r ${month}_bkp_files.zip ${month}_bkp_files
done
else
echo "No Files exists to backup"
fi

Also please help me if this script can be write some more better way.

Thanks in advance!

cd /path/folder1
if [ -f *.* ]; then
ls -lrt | awk -v '/^\-/{print $6,$NF}' | while read month filename
do
mkdir -p /path/folder1/${month}_bkp_files
mv ${filename} /path/folder1/${month}_bkp_files
zip -r ${month}_bkp_files.zip ${month}_bkp_files
rm ${month}_bkp_files
done
else
echo "No Files exists to backup"
fi

Thanks for ur response!

I getting the below error message when i try to run the above,

rm: cannot remove 'Oct_bkp_files': Is a directory

When I run second time the already zipped folders should not get zipped again.

if [ -f *.* ]; - I am using this file exists checking if statement. how to enable this only for the current directory and not for its subdirectories?

Thanks!

If those are files it will work...

If those are directories then use

rm -rf

add this line to get only files

ls -lrt | awk '/^\-/ && ! /\.zip$/{print $6,$NF}'

Thanks!

rm -rf ${month}_bkp_files

it will remove only the directories under
/b2bintshr/edi/SrcFiles/test right?

parent directories will not be deleted correct?

thanks!

Yes it will not remove parent directories. Just take care that you don't have any spaces between them :smiley:

1 Like

Thanks! it is working fine.

This is why one should always quote avidly:

rm -rf "${month}_bkp_files"

Notice the double quotes. They will make sure even file names with spaces in them will get handled correctly. Try it:

# mkdir testdir
# cd testdir
# touch a; touch b; touch "a b"
# x="a b"
# rm $x                # will remove "a" and "b", but not "a b"
# rm "$x"              # will remove "a b" but leave "a" and "b" alone

CAUTION: "eval" will eat up the quotes:

# eval rm "$x"         # will remove "a" and "b" again, like the unquoted line

I hope this helps.

bakunin