-1

I want to delete some directories that contain mounted (--bind) subdirs. I use following for loop in a script file named .du .

for dirname in $1; do                                                                                                                                         
    sudo umount $dirname/images/Spielplatz
    sudo umount $dirname/sounds/Spielplatz
    sudo rm -r $dirname
done

I call the script file with

.du Test*

to delete all directories that begin with "Test". But it only deletes the first one. So I have to call .du for every directory.

How do I have to write it, so that it processes all of them with one call?

SaintHax
  • 1,875
  • 11
  • 16
Michael
  • 6,823
  • 11
  • 54
  • 84
  • 1
    @WalterA, absolutely not `in $*` -- that'll break horrifically if you have whitespace in your names. – Charles Duffy May 23 '16 at 16:24
  • 1
    BTW, you've got other bugs here as well. `rm -r $dirname` is not going to behave the way you want with all possible names. Make it `umount "$dirname/images/Spielplatz"` and `rm -r -- "$dirname"` -- with the quotes -- for reliability, and consider running your scripts through http://shellcheck.net/ to catch that kind of issue. – Charles Duffy May 23 '16 at 16:31

2 Answers2

1

On UNIX, unlike DOS/Windows, glob expressions are expanded before a program starts. Thus:

.du Test*

runs something like .du Test1 Test2 Test3 (if those are the files that match the glob). Thus, $1 refers to Test1, whereas $2 would be Test2, etc. The program has no way of knowing that it was originally invoked with Test* on the command line; all it's given is the post-expansion array.

To iterate over all elements in this array, use:

for dirname in "$@"; do
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
1

It's doing exactly what you are asking for -- $1 is the first argument. To loop over all arguments, use "$@":

for dirname in "$@"; do

You are even allowed to leave this out because it's the default;

for dirname; do
tripleee
  • 175,061
  • 34
  • 275
  • 318