6

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

This:

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.

Eg:

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

How can I do this?

Cyrus
  • 5,441
  • 1
  • 22
  • 30
Nathan Long
  • 26,015
  • 36
  • 102
  • 139

2 Answers2

10

Quoting prevents globbing. Try this with GNU bash:

rm "$DIR"/*.MOV
Cyrus
  • 5,441
  • 1
  • 22
  • 30
  • 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 09:53
  • jena, it won't work if $DIR has spaces in it—try it with `x="a b"; echo ${x}` (notice the two spaces in the variable value), which "echo" expands to two arguments before adding a single space between them. – Mihai Danila Jun 09 '20 at 20:16
  • @MihaiDanila - it works just fine. use quotes AND braces (sorry code in comments looks terrible) : `$ x="a b";echo ${x} a b $ x="a b";echo "${x}" a b ` – keithpjolley Jan 21 '21 at 23:05
-1

A workaround:

for FILE in `ls "$DIR" | grep .MOV`; do
  rm "$DIR/$FILE"
done
Nathan Long
  • 26,015
  • 36
  • 102
  • 139
  • 1
    [Why you shouldn't parse the output of `ls`](https://mywiki.wooledge.org/ParsingLs). – Kamil Maciorowski Sep 29 '18 at 05:52
  • @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
  • 1
    @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