2

Due to my lack of knowledge in Bash, I come to you with a trivial problem. I have an 'Apps' directory of 41 folders. In each folder, there is a css subdirectory containing a glue1.css file. My goal is to remove that css file via a bash loop, but I need to exempt two folders: ad and glue-resources.

I need to exempt the ad folder because there is no css file. I want to prevent the following error from occurring upon execution:

rm: ad/css/glue1.css: No such file or directory

Consider this hypothetical directory (lacking 41 folders for brevity):

Apps
  ad
    css
      (empty)
  glue-resources
    css
      glue1.css (keep this file!)
  profile
    css
      glue1.css (remove this file!)
  ...

Here is the code I have so far. It should call rm on the glue1.css file if the parent directory path is NOT equal to glue-resources/css/ or ad/css/.

for dir in **/css/; do
if [[ "${dir}" != 'glue-resources/css/' || "${dir}" != 'ad/css/' ]]; then
    rm "${dir}"glue1.css
fi
done

The above code results doesn't work. I get the same 'No such file or directory' error and the glue1.css file in glue-resources/css has been removed. I'm not quite sure why it doesn't work—I read somewhere that if you use [[ and ]] you can combine multiple conditions.

I think the problem is that I don't understand how multiple conditions in bash work. The following versions of the code work.

for dir in **/css/; do
if [[ "${dir}" != 'glue-resources/css/' ]]; then
    rm "${dir}"glue1.css
fi
done


for dir in **/css/; do
if [[ "${dir}" != 'ad/css/' ]]; then
    rm "${dir}"glue1.css
fi
done

My attempt to add multiple conditions to the if statement failed.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Matthew
  • 2,158
  • 7
  • 30
  • 52
  • Try out [shellcheck](http://www.shellcheck.net), it would have autodetected [this issue](https://github.com/koalaman/shellcheck/wiki/SC2055). – that other guy Aug 08 '16 at 04:28

2 Answers2

2

Because || represents logical-OR, the following condition will always return true:

[[ "${dir}" != 'glue-resources/css/' || "${dir}" != 'ad/css/' ]]

I suspect that what you want is:

[[ "${dir}" != 'glue-resources/css/' && "${dir}" != 'ad/css/' ]]

&& is logical-AND. It requires that both conditions be met at the same time.

John1024
  • 109,961
  • 14
  • 137
  • 171
0

Perhaps you could avoid the loop and do something like this:

find . -path ./glue-resources -prune -o -name glue1.css | xargs -I [] rm []
saxitoxin
  • 418
  • 3
  • 6