Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Brace expansion in scripts not working due to unwanted escaping

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?

like image 202
Roland Avatar asked Jul 01 '11 14:07

Roland


People also ask

What is Brace expansion in bash?

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.

Does bash ignore whitespace?

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.

What do curly braces do in bash?

The curly braces tell the shell interpreter where the end of the variable name is.

What does expansion mean in bash?

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 .


1 Answers

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}"
like image 50
Michael Lowman Avatar answered Oct 12 '22 01:10

Michael Lowman