Run a command multiple times using a list of curly braces

When I needed to execute the command several times with a different argument, I used this approach (without fully understanding it):

touch {a,b,c} 

Which is equivalent:

 touch a touch b touch c 

I think the same could be done with the following loop:

 for file in {a,b,c}; do touch $file; done 

However, I came across a case where this does not work:

 pear channel-discover {"pear.phpunit.de","pear.symfony-project.com"} 

I have a few questions:

  • What is the name of what happens in the first example and what exactly happens?
  • Is it better to use this approach for simple things and not for in-in loops?
  • Why doesn't the pear team work like that? Should the script command implement some methods to handle such arguments, or is the shell responsible for this?
+7
source share
3 answers

This is called a Bracket Extension , which expands to a list of space-separated lines.

So touch {a,b,c} will be equivalent

 touch abc 

So far, touch {a,b,c}x will be equivalent:

 touch ax bx cx 

The pear command will execute as:

 pear channel-discover pear.phpunit.de pear.symfony-project.com 

which may not be what you expected. If you want the command to run once for each line, use a for loop (which answers your second question) or use a combination of parenthesis extension and xargs.

+10
source

The problem is that, contrary to your expectation, the expansion of the bracket

 touch {a,b,c} 

equivalently

 touch abc # NOT 3 separate invocations. 

(Use echo {a,b,c} to check). It seems that pear channel-discover does not accept two arguments. You will probably see the same error with

 pear channel-discover pear.phpunit.de pear.symfony-project.com 
+5
source

You have two options:

 for i in "pear.phpunit.de" "pear.symfony-project.com" do pear channel-discover "$i" done 

Or single line (but calling xargs instead of internal bash):

 echo "pear.phpunit.de" "pear.symfony-project.com" | xargs -n1 pear channel-discover 

The first, of course, is easier to read by a person, the effectiveness of time will be basically the same.

0
source

All Articles