简体   繁体   English

变量替换无法将 --exclude 选项传递给 tar 命令

[英]Variable substitution not working to pass --exclude options to tar command

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):我正在尝试通过 env var 将一些--exclude语句传递给我的tar命令(实际上我会传递几个--exclude语句,并尝试通过将定义放在单独的行上来提高可读性):

# EXCLUDE_STUFF="--exclude='/captain/generated'"
# tar ${EXCLUDE_STUFF} -cvzf /dev/null /captain
/captain/
/captain/generated/
/captain/generated/registry-auth
... etc ...

ie it's not excluding the folder I've specified.即它不排除我指定的文件夹。 It doesn't make a difference if I surround ${EXCLUDE_STUFF} in quotes.如果我用引号将${EXCLUDE_STUFF}括起来并没有什么不同。

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 ...

ie the specified folder has been excluded.即指定的文件夹被排除。

So why is the variable substitution not working in this context?那么为什么变量替换在这种情况下不起作用呢?

why is the variable substitution not working in this context?为什么变量替换在这种情况下不起作用?

After assignment the variable EXCLUDE_STUFF contains literally the string --exclude='/captain/generated' .赋值后,变量EXCLUDE_STUFF包含字符串--exclude --exclude='/captain/generated'

You are passing --exclude='/captain/generated' from the variable substitution.您正在从变量替换中传递--exclude='/captain/generated' 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.因为没有相对于您当前工作目录的字面名称为'的目录,所以'/captain/generated'不匹配任何内容,因此它不排除任何内容。

In short tar --exclude='/captain/generated' is not the same as tar "--exclude='/captain/generated'" .简而言之tar --exclude='/captain/generated'tar "--exclude='/captain/generated'"不同。

In this case, just在这种情况下,只需

exclude_stuff="--exclude=/captain/generated"
tar "$exclude_stuff" ...

Or use bash arrays:或者使用 bash arrays:

exclude_stuff=( --exclude='/captain/generated' )  # note: quotes are interpreted
tar "${exclude_stuff[@]}" ...

Read https://mywiki.wooledge.org/BashFAQ/050 .阅读https://mywiki.wooledge.org/BashFAQ/050 Research shell quoting, how it works, and when by it, research word splitting expansion and filename expansion.研究 shell 引用,它是如何工作的,以及何时使用它,研究分词扩展和文件名扩展。 Check your scripts with https://shellcheck.net .使用https://shellcheck.net检查您的脚本。 Prefer to use lower case variables for script local variables.喜欢使用小写变量作为脚本局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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