tomashauser
tomashauser

Reputation: 571

Tar puts additional backslash in front of every backslash in bash

I have an array $files which contains addresses of files I want to tar together. I do it like this: tar czf "output.tgz" "${files[@]}". It all works until there are is a file with spaces in its name. For that I use path="${path// /'\ '}" which replaces all <space> with \<space> and after that I'll add it like this files+=("<space>$path"); into the $files array.

When I try to do it with just a single test file called main and space.c, the $files is set correctly on: /home/tom/Desktop/main\ and\ space.c when I call echo "Files array looks like this: $files" just before tarring, but when the program comes to the tarring on the next line, I get the error:

tar: /home/tom/Desktop/main\\ and\\ space.c: Cannot stat: No such file or directory

Can I make tar avoid putting the additional backslashes there?

Upvotes: 0

Views: 271

Answers (1)

chepner
chepner

Reputation: 531918

You are fighting against your array in the first place. Just add properly quoted names to the array; the shell will handle the contents of the array for you.

$ 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

Upvotes: 2

Related Questions