Home > OS >  Find and delete files using shell
Find and delete files using shell

Time:09-07

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'
}
  • Related