I want to do something like this in a bash script. I'm using bash 4.1.10
.
# rm -rf /some/path/{folder1,folder2,folder3}
Works nicely (and as expected) from the shell itself. It deletes the 3 desired folders leaving all others untouched.
When I put it into script something unwanted happens. For example, my script:
#!/bin/bash
set -x
VAR="folder1,folder2,folder3"
rm -rf /some/path/{$VAR}
When I execute this script, the folders are not deleted.
I think this is due to the fact that some unwanted quoting is occurring. Output from the script using #!/bin/bash -x
:
rm -rf '/some/path/{folder1,folder2,folder3}'
which of course cannot succeed due to the '
marks.
How can I get this working within my script?
Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to filename expansion (see Filename Expansion), but the filenames generated need not exist.
Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.
The curly braces tell the shell interpreter where the end of the variable name is.
Bash uses the value formed by expanding the rest of parameter as the new parameter ; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter . This is known as indirect expansion .
According to the man page:
The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion.
So to get around this, add another level of expansion:
eval "rm -rf /some/path/{$VAR}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With