You are not logged in.
Hello,
I just learned about being able to use shopt and bash together to be able exclude files/folders while removing. I find myself doing this at times and I'd like to have a versatile command around. It's pretty simple, what you do is:
#!/bin/bash
shopt -s extglob
rm -rf !("$1")
And it works great. However, I'd like to be able to specify more than one file at times. Putting it in a for loop won't do because the remaining files won't be there on the next pass. I'm thinking of just specifying $1 to $9 (rm -rf !("$1") !("$2") !("$3")... It would work but it's not very elegant. Is there a another way to approach this, or would it get too complex. (probably and easy way to do this, just nothing coming to mind).
Setting Up a Scripting Environment | Proud donor to wikipedia - link
Offline
#!/bin/bash
IFS="|$IFS"
shopt -s extglob
rm -rf !("$*")
Haven't tried it out though.
Last edited by fflarex (2010-03-07 02:36:22)
Offline
Nope, no luck there. Removed everything in the directory.
Note to self: learn about IFS
Thanks for the try, fflarex.
Setting Up a Scripting Environment | Proud donor to wikipedia - link
Offline
#!/bin/sh
IFS="|$IFS"
bash -O extglob -c 'rm -rf !($0)' "$*"
I tested it this time. Seems to work, but you should be really careful with it. I haven't tested any corner cases, and I don't really know what would happen to files with spaces or pipes in their names, or directory names with a slash appended. You may need to pipe 'echo "$*"' through sed or something to make sure you don't accidentally delete anything important.
Last edited by fflarex (2010-03-07 05:36:35)
Offline
Initial test ran good, choose two files and it saved them, very nice.
and I don't really know what would happen to files with spaces or pipes in their names, or directory names with a slash appended.
Choose a large directory that had hyphens, and subdirectories and selected a file and folder with no problems. Did it again and added a file with a space. If I choose files that were not spaced, it did good. However, if I choose a file with a space in it, it would do nothing (which isn't too bad, nothing disastrous this way would occur ).
You may need to pipe 'echo "$*"' through sed or something to make sure you don't accidentally delete anything important.
Yeah, were you thinking about handling spaces? Perhaps something like this: sed 's/ /\\\ /g' , just to add the backslashes??
I tested it this time. Seems to work, but you should be really careful with it. I haven't tested any corner cases...
Pretty happy with the initial run, this will save me a good deal of time as I tend to do a good amount of file moving. Appreciate the help.
Last edited by Gen2ly (2010-03-08 01:26:13)
Setting Up a Scripting Environment | Proud donor to wikipedia - link
Offline