Tar在bash中的每个反斜杠前面加上了额外的反斜杠

问题描述

我有一个数组$files,其中包含我想一起压缩的文件的地址。我这样做是这样的:tar czf "output.tgz" "${files[@]}"。一切正常,直到名称中包含空格的文件为止。为此,我使用path="${path// /'\ '}"将所有<space>替换为\<space>,然后将类似files+=("<space>$path");内容添加$files数组中。

当我尝试仅使用一个名为main and space.c的测试文件来完成操作时,$files的设置正确:/home/tom/Desktop/main\ and\ space.c当我在焦油之前调用echo "Files array looks like this: $files"时,但是当程序到达下一行时,出现错误

tar:/ home / tom / Desktop / main \\和\\ space.c:无法统计:没有这样的文件或目录

我可以使tar避免在其中加上其他反斜杠吗?

解决方法

首先,您要与阵列作战。只需在数组中添加正确引用的名称即可;该外壳程序将为您处理数组的内容。

$ files=()
$ files+=("test 1.txt")
$ files+=("test 2.txt")
$ files+=("test 3.txt" "test 4.txt")
$ tar czf output.tgz "${files[@]}"
$ tar tzf output.tgz
test 1.txt
test 2.txt
test 3.txt
test 4.txt