Home > Mobile >  bash: delete filles matching specific pattern if they are present in the directory
bash: delete filles matching specific pattern if they are present in the directory

Time:10-13

I am trying to check the presence of the all filles started from the pattern in workdir and then to remove all of them if they are exist:

target='file_pattern_to_be_removed'
if [ -e "${workdir}"/${target}*.dat ]; then rm "${workdir}"/${target}*.dat; fi

which produces

./test.sh: line 482: [: too many arguments

Assuming that in the workdir there are totally 10 filles started form the pattern how would be better to execute such condition?

CodePudding user response:

[ -e ... ] can't handle multiple parameters, but you don't actually have to check: with

shopt -s nullglob
rm -f "$workdir/$target"*.dat

you delete files if there are matches, and nothing happens if there is no match. The nullglob shell option is set so the glob expands to the empty string if nothing matches (else it would try to delete a file containing a literal *), and the -f option suppresses a warning about missing files if there was nothing to delete.

  • Related