I have a directory where there are subdirectories which have numbers as directories. For example I have a parent directory test now I have some subdirectories like 1,2,3,4,5,6,7.

Now I have a local exported variable like export a=3. I want to delete directories that are above or equal to $a but below or equal to $a+2, So I want to delete directories 3, 4,5.

Also if I don't know the least number directory and I want to delete everything below or equal to $a so the directories 1,2,3 gets deleted. How can I achieve this?

I tried rm -rf {$a..$($a+3)} and rm -rf {<$a}, it didn't work, I tried so many other things but not successful.

  • 1
    you only have one $a, and you do calculating lower and upper both based on the $a, so what do mean when you are saying "Also if I don't know the least number directory and I want to delete everything below or equal to <$a"? Oct 6, 2021 at 17:51
  • You tagged bash, but would you be open to a zsh-based solution?
    – Jeff Schaller
    Oct 6, 2021 at 17:53

2 Answers 2


You could use zsh instead of bash which has a glob operator to match on range of decimal integer numbers and can also restrict globs to files of a given type (such as directory in your case).

The <3-5> glob matches on strings that make up numbers 3 to 5, which includes 3, 4 and 5 but also 03, 003. The digits have to be literal though. You can still use variables, if you do things like:

rm -rf test/$~range(/)

Where $~range forces the parameter expansion to be taken as a pattern, and (/) restricts to files of type directory.

You can do without the intermediary variable if you use an anonymous function:

() { rm -rf test/$~1(/); } "<$a-$((a+2))>"

To match on numbers that are less than 4, just use <0-3> or <-3>. To also include negative numbers: (-<->|<0-3>).

Your {$a..$((a+2))} approach would work in zsh, though that expands to 3, 4, 5 regardless of whether files by that name exist or not (and wouldn't match on 03, 00005...). The fact that it doesn't work is a limitation that affects only the bash shell (among the shells that support {x..y} which actually is a zsh invention).


Assuming there are only directories with numbers as names then we can use:

rm -rf $(seq $(ls | head -1) $a)

Your Answer

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