简体   繁体   中英

npm script to remove all files in directory except files with certain extensions (mac os)

I know there are a lot of similar questions on here but I haven't found the answer I'm searching for. Here is the command I am trying to use in a npm script.

rm -rf public/!(*.md)

I have enabled extended globing by using the command shopt -s extglob and the command runs fine in the terminal. The issue I have is that it doesn't run when I use the same command as an npm script.

The Script

"scripts": {
   // ...
   "clean:public": "rm -rf public/!(*.md)",
   //...
}

The error I get in my terminal when running the script

> rm -rf public/!(*.md)

sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `rm -rf public/**/!(*.md)'

Possible solutions that have failed...

  1. Quoting the glob rm -rf 'public/!(*.md)'
    • This got rid of the error but the script doesn't remove the files.
  2. I also tried quoting the glob with escaped double quotes and had the same result.
  3. I tried escaping the parentheses and got a json parse error.

What I think the problem is...

I just learned that npm run scripts don't use the shell of the user that runs the command. Im not sure how to solve this except by maybe installing additional npm packages? If that's the case, which packages should I install?

Run your script under bash. As you see from the error message, ie sh: , this is not bash. If the script has to be run under sh, sh-wrapper script. For instance, if your current bash script (containing the rm or what ever you need to do) is foo.sh , write the command as:

"clean:public": "bash /path/to/your/script/foo.sh"

Ran into the same issue and got it working with a recommendation of the del-cli package.

npm install --save-dev del-cli

And then in package.json

"clean:public": "del public/** '!public/*.md'"

For those curious, del can be used outside the current directory with the --force flag

"clean:public": "del ../some-upper-dir/** '!../some-upper-dir/*.md' -f"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM