Skip to main content

Bash script to tar – Quoting issue [Resolved]

This question already has an answer here:

I have a script that takes filenames as positional parameters. I perform a few operations on these and then tar them. Currently my script is not working. The echo line is there for debugging purposes.

Please clarify this statement

But when I try to tar with in the script if can file the file I want to tar.


while [[ $# > 0 ]]; do
    files=$files" "\"${key}\"

echo tar -cvf backup.tar $files
tar -cvf backup.tar $files


tar -cvf backup.tar "test.txt"
tar: "test.txt": Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

I am using the double quotes around the filename (test.txt) as I want to handle files with spaces.

If I were to remove the quotes in the script (\"), it will work but then I can’t handle filenames with spaces.

Any ideas?

Question Credit: goldengreen
Question Reference
Asked October 15, 2017
Posted Under: Unix Linux
1 Answers

If you are always using all the params then just call tar like this: tar -cvf backup.tar "$@". Otherwise, if you are selecting a subset (though you don't show it) then build up the file list in an array like this:

declare -a files
while [[ $# > 0 ]]; do
    # assume some filtering goes on here

tar -cvf backup.tar "${files[@]}"

credit: Jesse_b
Answered October 15, 2017
excellent this work using the array and quoting when adding to the array. Thanks a million. – goldengreen yesterday
 CanDoerz  5 months ago
Your Answer