bashmkdir

Bash : passing variable as a parameter for mkdir


I am trying to pass the variable $subdir which has the following string value :

subdir="subdir{1..5}/subdir{1..5}/subdir{1..5}/subdir{1..5}"

into the command mkdir in the following way :

mkdir -p $subdir

However, this is creating the following structure :

enter image description here

When I run this :

mkdir -p subdir{1..5}/subdir{1..5}/subdir{1..5}/subdir{1..5}

I get the structure that I want :

enter image description here

How do I make the command work while passing the path as a variable. I tried using quotes, but it doesn't work.


Solution

  • Brace expansion need to be unquoted, so:

    mkdir -p subdir{1..5}/subdir{1..5}/subdir{1..5}/subdir{1..5}
    

    Check https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html

    If you really need a variable:

    eval mkdir -p "$path"
    

    warning Be sure that "$path" is not generated by CGI script, or by any random user input.