I have a bash script where $DIR is a directory name that may contain spaces.


rm "$DIR/*.MOV"

gives the error "No such file or directory". There is no file literally named "*.MOV"; I want the * to expand into multiple arguments - one per matching filename.


rm some\ folder/foo.MOV some\ folder/bar.MOV

How can I do this?


Quoting prevents globbing. Try this with GNU bash:

rm "$DIR"/*.MOV
  • I usually use {} when I want to append or modify something about my variable, like this: ${DIR}/*.MOV. I don't know which of these is better, but using {} works for my use cases every time. – jena Nov 15 '18 at 9:53

A workaround:

for FILE in `ls "$DIR" | grep .MOV`; do
  rm "$DIR/$FILE"
  • @KamilMaciorowski - Isn't it just better to not use newlines in your filenames? Who would do that anyway? I'm not a sysadmin, I'm working on datafiles produced by me and my colleagues and although one of them is crazy (ADHD among other things), putting newlines into filenames is just crazy and I would have such filename fixed. In the link they even suggest putting timestamps into filename just to avoid not putting newlines in them - wtf? – jena Nov 15 '18 at 10:08
  • @jena Isn't just better to not spill oil on your floor? Who would do that anyway? Maybe a rogue who wants to exploit the fact you're careless. Besides: accidents happen, poorly written archivers unpack files with strange names etc. If you want to parse ls, it's your choice, you have been warned. People who'd like to use this answer in their projects, where they deal with filenames of unknown origin, should be warned as well before they rm too much. – Kamil Maciorowski Nov 15 '18 at 10:41
  • I partially agree, as I said, I'm not a sysadmin but a scientist, so I generally work on secured clusters on files produced by me & colleagues. If I use standard tools and work with sensible people, I can parse ls just fine, am I right? – jena Nov 15 '18 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.