Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

[ -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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading