I want to delete some files from the working directory, but first list the files to be deleted:
#!/usr/bin/env zsh
tput bold;
tput setaf 1;
echo "You are about to DELETE ALL auxillary files and Tmp files"
echo "These are the files to be deleted:"
tput sgr0;
for ext in log out aux dvi lof lot bit idx glo bbl bcf ilg toc ind out blg fdb_latexmk fls run.xml pyg pyg.out
do
find . -type f -name "*.$ext" -not -path "./.git/*" -print
done
find Tmp/ -type f
tput setaf 3;
read -s -k "?Press any key to purge!"$'\n'
tput sgr0;
for ext in log out aux dvi lof lot bit idx glo bbl bcf ilg toc ind out blg fdb_latexmk fls run.xml pyg pyg.out
do
find . -type f -name "*.$ext" -not -path "./.git/*" -delete
done
find Tmp/ -type f -delete
tput bold;
tput setaf 1;
echo "DONE"
I was wondering if it is possible to avoid repeating a large chunk of code twice.
CodePudding user response:
setopt extendedglob
local -a ext=(
log out aux dvi lof lot bit idx glo bbl bcf ilg toc ind out blg
fdb_latexmk fls run.xml pyg pyg.out
)
local -a files=(
**/*.${^ext}~./.git/*(N.)
Tmp/*(N.)
)
print -nP '%B%F{1}'
{
if ! (( $#files )); then
print No files to delete!
return 1
fi
print -P You are about to DELETE ALL auxiliary files and Tmp \
files in '%~'
print -P These are the files to be deleted:
} always {
print -nP '%b%f'
}
ls $files
{
print -nP '%F{3}'
if ! read -q '?Purge? [yn] '; then
print -P '\nPurge aborted.'
return 1
fi
rm -f $files
print -P '\n%B%F{1}DONE'
} always {
print -nP '%b%f'
}
extendedglob
enables all kinds of handy additional pattern matchers, such as~
for negation.- The parameter expansion
${…}
causes an array to be treated as a brace expansion. - By default, non-matching patterns in Zsh cause an error. The glob qualifier
(N)
causes them to be removed instead. (.)
matches plain files only.- Passing the
-P
flag to theprint
builtin command lets you use prompt escape sequences. - An
always
clause always executes after the preceding block, even after areturn
statement, but never changes the return value. read -q
reads one character and evaluates totrue
only if that character isy
orY
.