Reputation: 1709
I have a bunch of files in a directory that I want zipped:
for i in $dir/*; do
if [[ ! "$i" =~ "zip" ]]; then
zip $i
else
echo "$i has already been zipped"
fi
done
If I populate the directory with a new files and run the script again, it will re-zip all files that don't contain the string "zip". How do I skip those files that are unzipped but already have a zip file in the same directory?
For example, the script should not zip testing.log
again because it already has a zip version in the same directory:
testing.log testing.log.zip
UPDATE - 03/15/2018
Thanks for all your feedback! The script now looks like:
for i in $dir/*.log; do
if [[ ! -f "${i}.zip" ]]; then
zip $i
else
echo "$i has already been zipped"
fi
done
Upvotes: 2
Views: 1567
Reputation: 2970
for i in $dir/*; do
if [ -f "${i}.zip" -o "${i}" = "${i%.zip}" ]; then
echo "${i} has already been zipped"
continue
fi
zip $i
done
Where [ -f "${i}.zip" ]
checks the existence of the corresponding zip file and [ "${i}" = "${i%.zip}" ]
checks whether the file itself is a zip file.
Upvotes: 2
Reputation: 5591
You better manage a history file. For example if you are zipping mylog.log file put that file in a history file like below
echo "$i" >> history.txt
zip $i
and next time while you start the same script it should check whether that file is already available in that history.txt
file or not. If available in history file do not zip it. So your final script will be look like below:-
if grep "$i" history.txt ; then
echo "$i already zipped
else
echo "$i" >> history.txt
zip $i
fi
At the very beginning create a history file manually else if
condition will give you an error message.
Hope this will help
Upvotes: 1
Reputation: 84551
You can even use a character class to help with initial file selection by excluding files with zip
in their extension. For example
for i in "$dir"/*.[^z]*; do ## exclude all files w/ext beginning with 'z'
zip "$i"
done
Just another approach to take that comes at the issue from another angle.
Upvotes: 2
Reputation: 1947
I would go with something like
for i in $dir/*; do
if [ -z ${i##*.zip} ]; then
# $i ends with ".zip"
echo "already a zip file: $i"
elif [ -f ${i}.zip ] ; then
# there already exists a zipped file named $i.zip
echo "already has zipped sibling: $i"
else
# actually zip $i into $i.zip
zip $i.zip $i
fi
done
Upvotes: 1