0

In the code below:

#!/bin/bash

echo AAAAAA > a.txt
echo BBBBBB > b.txt
echo CCCCCC > c.txt

files="a.txt b.txt c.txt"

tar -cvf archive1.tar $files  # this line works

tar -cvf archive2.tar "$files"  # this line doesn't work - why???

the first tar command works fine, but the 2nd tar line, with "$files" does not. Why is this?

Angus Comber
  • 9,316
  • 14
  • 59
  • 107
  • 3
    When you use `"$files"` all the filenames are considered a single argument. Better to use array: `files=(a.txt b.txt c.txt)` and use it as: `tar -cvf archive2.tar "${files[@]}"` – anubhava Aug 23 '22 at 15:30
  • 1
    It's looking for _one file_ named `a.txt b.txt c.txt` (where the spaces are part of the filename). Anubhava is right -- you should use an array; that way filenames you literally can't represent in a string that's going to go through word-splitting and expansion are still possible / won't break your script. (Think about `files=( "name with spaces.txt" "*** name with globs *** .txt" )`) – Charles Duffy Aug 23 '22 at 15:33

0 Answers0