0

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.

SNIPPET

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

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

OUTPUT:

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?

  • 1
    Why not just pass the file params directly to tar? tar -cvf backup.tar "$@" ? – B Layer Oct 14 '17 at 00:29
  • what about: files="$files \"${key}\""? Or use an array...files+=("$key") and then tar -cvf backup.tar ${files[@]} – jesse_b Oct 14 '17 at 00:32
  • Wouldn't he need the $files variable in the tar statement unquoted though? Otherwise, wont they be treated as one argument? – jesse_b Oct 14 '17 at 00:44
  • Use capital letters. – peterh Oct 14 '17 at 01:34
  • @Scott et al. Bit of a stretch to call this a dup of that question don't you think? Yes, OP appears to have some misunderstanding of quoting but that's a peripheral issue. The primary issue is that a string is not the answer. I recommended an array instead. If I didn't answer do you think OP would be able to fix things by reading that thread? (Heck, would OP even read all of that? Seems like making someone get a drink of water from a firehose.) Wonder if there's a more focused thread to point to... – B Layer Oct 15 '17 at 15:21
  • @BLayer: The answer that I linked to gives the exact same answer that you did. – Scott - Слава Україні Oct 15 '17 at 17:38
  • @Scott Really? I didn't see it when I skimmed through. I don't have time to read all of it so I'll take your word for it. The fire hose comment is still apt but at least it is a duplicate, technically. Thanks. – B Layer Oct 15 '17 at 20:32

1 Answers1

3

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
    key="$1"
    shift
    # assume some filtering goes on here
    files+=("$key")
 done

tar -cvf backup.tar "${files[@]}"
jesse_b
  • 37,005
B Layer
  • 5,171