0

Maybe this is a pretty silly question. I'm a beginner at bash scripting and I'm not able to properly while trying to execute the command.

#!bin/bash noise={5,10,15}dB mkdir $(echo $noise) 

I want to create 3 directories 5dB,10dB, and 15dB in a bash script where {5,10,15}dB is given as a positional argument. The script doesn't perform the brace expansion and gives a folder {5,10,15}dB. Can anyone help me??

2
  • 1
    if you intend to use $noise elsewhere, maybe your are looking for array not bash expansion. Commented Feb 26, 2020 at 16:44
  • Ok, I'll try using an array. Thanks! Commented Feb 26, 2020 at 21:58

2 Answers 2

1

There is no need to store it in a variable first. Braces don't expand on the right hand side of variable assignment anyway so your variable is becoming literally {5,10,15}dB.

You can just do:

mkdir {5,10,15}dB 

Additionally there is no need to echo a variable inside command substitution, all that is doing is expanding the contents of the variable so:

mkdir $(echo $noise) 

Is no different than:

mkdir $noise 
1

I think it is the expansion order that confused you. Bash performs them in a specific order, and it's the brace expansion that comes first, followed by the variable expansion. This is why the brace expansion did not work in your example.

You can use eval to force bash into performing the expansion:

noise={5,10,15}dB # BAD IDEA, FOR DEMONSTRATION PURPOSES ONLY eval mkdir $noise 

However, generally it's bad practice because if there's some malicious code inside $noise, it will be executed, as well.

As @Archemar points out in a comment, using an array might be a better idea, e.g.

noise=(5 10 15) mkdir "${arr[@]/%/dB}" 

If you're passing the directory names from the command line, there should be no issues with brace expansion because it will be done by the interactive shell when you call the script. In other words, the following will work:

$ cat script.sh #!/bin/bash mkdir "$@" $ ./script.sh {5,10,15}dB 
2
  • I see, I guess I'll try using an array, but actually noise variable is initialised through command line argument. But I'll see if I can use it. Thanks for the suggestion Commented Feb 26, 2020 at 22:00
  • @AnubhabGhosh In that case there should be no problem with the brace expansion at all, see the updated answer. Commented Feb 26, 2020 at 22:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.