I am trying to pass some --exclude
statements to my tar
command via an env var (in reality I would be passing several --exclude
statements, and trying to improve readability by putting the definition on a separate line):
# EXCLUDE_STUFF="--exclude='/captain/generated'"
# tar ${EXCLUDE_STUFF} -cvzf /dev/null /captain
/captain/
/captain/generated/
/captain/generated/registry-auth
... etc ...
i.e. it's not excluding the folder I've specified. It doesn't make a difference if I surround ${EXCLUDE_STUFF}
in quotes.
This is what I get when I echo the above command:
# echo tar ${EXCLUDE_STUFF} -cvzf /dev/null /captain
tar --exclude='/captain/generated' -cvzf /dev/null /captain
So it looks like the command is correct. And when I run the expanded command directly, I get:
# tar --exclude='/captain/generated' -cvzf /dev/null /captain
/captain/
/captain/temp/
/captain/data/
... etc ...
i.e. the specified folder has been excluded.
So why is the variable substitution not working in this context?
CodePudding user response:
why is the variable substitution not working in this context?
After assignment the variable EXCLUDE_STUFF
contains literally the string --exclude='/captain/generated'
.
You are passing --exclude='/captain/generated'
from the variable substitution. Because there is no directory named literally '
relative to your current working directory, '/captain/generated'
does not match anything, so it does not exclude anything.
In short tar --exclude='/captain/generated'
is not the same as tar "--exclude='/captain/generated'"
.
In this case, just
exclude_stuff="--exclude=/captain/generated"
tar "$exclude_stuff" ...
Or use bash arrays:
exclude_stuff=( --exclude='/captain/generated' ) # note: quotes are interpreted
tar "${exclude_stuff[@]}" ...
Read https://mywiki.wooledge.org/BashFAQ/050 . Research shell quoting, how it works, and when by it, research word splitting expansion and filename expansion. Check your scripts with https://shellcheck.net . Prefer to use lower case variables for script local variables.