简体   繁体   English

tar exclude在bash脚本中不起作用

[英]tar exclude is not working inside the bash script

I am trying to create a tar file of a folder, which has a lot of files to be excluded. 我正在尝试创建一个文件夹的tar文件,其中有很多文件要排除。 So I wrote a script ( mytar ): 所以我写了一个脚本( mytar ):

#!/usr/bin/env bash

# more files to be included 
IGN=""
IGN="$IGN --exclude='notme.txt'"

tar --ignore-failed-read $IGN -cvf "$1" "$2"

# following command is working perfectly
# bash -c "tar --ignore-failed-read $IGN -cvf '$1' '$2'"

Test folder: 测试文件夹:

test/
    notme.txt
    test.txt
    test2.txt 

If I execute the script, it creates a tar file but doesn't exclude the files I have listed in IGN 如果执行脚本,它将创建一个tar文件,但不会排除我在IGN列出的文件
Apparently, the command is: 显然,该命令是:

tar --ignore-failed-read --exclude='notme.txt' -cvf test1.tar test  

The command is working perfectly fine if it's directly executing in the shell. 如果该命令直接在Shell中执行,则该命令运行正常。 Also I have found a workaround for the script: using bash -c in script file 我也找到了该脚本的解决方法:在脚本文件中使用bash -c

bash -c "tar --ignore-failed-read $IGN -cvf '$1' '$2'"

I am wondering and trying to figure out it, 我想知道并试图找出答案,

Why this simple command is not working without bash -c ? 如果没有bash -c为什么这个简单的命令不起作用?
Why it's working with bash -c ? 为什么它与bash -c一起使用?

Output: 输出:
First output shouldn't container notme.txt file like later 第一个输出不应像稍后那样容纳notme.txt文件
焦油排除流行病

UPDATE 1 script updated UPDATE 1脚本已更新

This has to do with the way bash expands variables in its shell. 这与bash在其shell中扩展变量的方式有关。

When you set: 设置时:

IGN="--exclude='notme.txt'"

it will be expanded as : 它将扩展为:

tar --ignore-failed-read '--exclude='\''notme.txt'\''' -cvf test1.tar test  

And as such tar will look to exlcude a file named \\''notme.txt'\\'' , which it won't find. 这样,tar将寻找一个名为\\''notme.txt'\\'' ,但找不到。

You may use: 您可以使用:

IGN=--exclude='notme.txt'

which will be be interpreted correctly after shell expansion and tar will know it, but I would rather suggest you use your variable to only store the file name to be excluded: 在shell扩展后,它将被正确解释,而tar会知道这一点,但我建议您使用变量仅存储要排除的文件名:

IGN="notme.txt"
tar --exclude="$IGN" -cvf ./test1.tar ./*

in following command single quotes are syntactical (not literal, filename argument is not literaly surounded by quotes) to prevent shell for splitting argument in the case it contains a space or a tab 在以下命令中,单引号在语法上是(语法上不是单引号,而在文件名参数上不能用引号引起来),以防止shell在包含空格或制表符的情况下拆分参数

tar --ignore-failed-read --exclude='notme.txt' -cvf test1.tar test  

the closest is to use array instead of string variable : 最接近的是使用数组而不是字符串变量:

ign=( --exclude='notme.txt' )
tar --ignore-failed-read "${ign[@]}" -cvf test1.tar test  

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

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