0

I am trying to create a mini-script for make a folder empty as npm task.

It is the style folder, which is filled by lessc.

In Linux shell it works:

me@work:~/path/to/my-app$ [ $(ls -A ./style/) ] && rm ./style/* # is is empty, nothing happens
me@work:~/path/to/my-app$ touch ./style/test
me@work:~/path/to/my-app$ ls -A ./style
test
me@work:~/path/to/my-app$ [ $(ls -A ./style/) ] && rm ./style/* # removing
me@work:~/path/to/my-app$ ls -A ./style # empty again

At this point the folder is empty and the task should run nonetheless. But it does not. This is my line in the scripts object in package.json: "clear:prod": "[ $(ls -A ./style/) ] && rm ./style/*"

me@work:~/path/to/my-app$ npm run dev

> hpc-app@0.9.2 dev
> run-s clear:* update:* compile:* eslint webpack:dev print-current-date


> hpc-app@0.9.2 clear:prod
> [ $(ls -A ./style/) ] && rm ./style/*

ERROR: "clear:prod" exited with 1.

The script works fine, when there is a file in the folder.

What am I doing wrong? Do I just not see the 1 when I run the shell command? Is there any way to do rm ./folder/* if it is empty without getting an error?

BairDev
  • 2,865
  • 4
  • 27
  • 50
  • 1
    "Do I just not see the 1 when I run the shell command?" YES. After doing that line in shell, do `echo $?` to see the exit status. Because the left side (the `[ ... ]` ccommand) failed, the right side wasn't executed and the whole command fails; that's what `&&` means. Consider instead doing (only) `rm -f style/*` -- if files exist that will remove them all (if you have permission), if no files exist it will do nothing 'successfully' (with exit status 0) – dave_thompson_085 Mar 07 '22 at 20:22
  • `[ $(...anything...) ]` is buggy, btw. **Always** quote your expansions: `[ "$(...anything...)" ]` -- otherwise the output of `...anything...` is word-split into multiple strings, and those strings are treated as test syntax if there's more than one of them, or causes an error if there are exactly zero (because `[ ]` isn't a valid command). – Charles Duffy Mar 07 '22 at 20:49
  • But as Dave says above -- just add the `-f` argument to `rm` to make an argument that doesn't exist no longer be an error. – Charles Duffy Mar 07 '22 at 20:51
  • Thanks @dave_thompson_085, @charles-duffy And when I think about it, it makes sense to have the `-f` flag. The expanding part is also true, but still need to play with it, because I need to use this mini-script in a *package.json* file. So in a double quoted string. – BairDev Mar 15 '22 at 08:15

0 Answers0