I encountered a very strange behavior when running below command, let me explain the issue:
Consider this simple bash script:
#!/bin/bash
zip -r /var/backup.zip /var/www -x /ignore_dir_1/\*
It compresses the whole www
folder recursively and excludes ignore_dir_1
which is perfectly fine.
Now, write that script like this:
#!/bin/bash
Exclude="/ignore_dir_1/\*"
zip -r /var/backup.zip /var/www -x $Exclude
It runs without error but does not exclude ignore_dir_1
.
Can anyone please explain this behavior?
- Disclaimer:
I have already tried the following alternatives:
Exclude="/ignore_dir_1/*"
Exclude="/ignore_dir_1/***"
Update:
Thanks to @pLumo, the problem solved by putting variable inside quotation like:
#!/bin/bash
Exclude="/ignore_dir_1/*"
zip -r /var/backup.zip /var/www -x "$Exclude"
Now, the problem is if Exclude
variable contain multiple folders, it does not work, I mean this:
#!/bin/bash
Exclude="/ignore_dir_1/* /ignore_dir_2/*"
zip -r /var/backup.zip /var/www -x "$Exclude"
I even tried "${Exclude}"
but no result.
-x "$Exclude"
, then your first alternative should work just fine. – pLumo Jul 18 '22 at 12:02For shell scripts with errors/syntax errors, please check them with the shellcheck program (or in the web shellcheck server at https://shellcheck.net) before posting here.
) that tool would have told you about the issue and provided a link to documentation about it. – Ed Morton Jul 18 '22 at 12:21zip
command toecho zip
and review the result when you run the script. You'll (hopefully) see why the command is failing to do what you want. (Hint: double-quote your variables when you use them.) – Chris Davies Jul 18 '22 at 13:51zip
.zip ... -x @excludes.txt
– don_aman Jul 18 '22 at 15:56