Search code examples
javascriptnode.jsbashubuntu-18.04shelljs

How do I use curly braces to create multiple directories in a single command via "shelljs"?


If you run this command in a Linux terminal:

mkdir -p ./dist/{articles,scripts,stylesheets}

It'll create the following folder tree (in the current directory):

dist
|- articles
|- scripts
|- stylesheets

The problem occurs when I try to do the same using the shelljs npm package.

For example, calling the following function:

shell.mkdir("-p", "./dist/{articles,scripts,stylesheets}");

Results in the following file tree being created:

dist
|- {articles,scripts,stylesheets}

In other words, it's a folder called dist that contains a subfolder called {articles,scripts,stylesheets}.

I've tried escaping the curly braces, like this:

shell.mkdir("-p", "./dist/\{articles,scripts,stylesheets\}");

It didn't work, so I doubled down and escaped the backslash:

shell.mkdir("-p", "./dist/\\{articles,scripts,stylesheets\\}");

That didn't work either, so I doubled down again and added an escaped backslash before the escaped backslash:

shell.mkdir("-p", "./dist/\\\\{articles,scripts,stylesheets\\\\}");

Which didn't work, but it did create a folder with a different name:

\\{articles,scripts,stylesheets\\}

How can I fix this problem?


Solution

  • shelljs mkdir() command takes as parameter a list or an array of directory names. It will not attempt to execute any command or sequence builder utility provided by bash, as we can see in source code. So there is no point to try to escape the braces.

    Instead you could send the raw command with exec():

    shell.exec("bash -c 'mkdir -p ./dist/{articles,scripts,stylesheets}'")