Reputation: 2436
I am trying to create an shell script (for use in an Automator action) that creates a .tar
archive of multiple files, some of which contain spaces as part of the path or filename. I have read through many questions on SO concerning tar creation, but couldn't piece together a working version.
My understanding is, it should go something like this:
tar -cf ~/Desktop/archive.tar "/path/somefile.txt" "/path2/some folder" "/path3/some other folder"
I have two drafts that look promising to me. I'm guessing, either could work.
From the OS X Finder the files get passed to the shell script either as arguments or to stdin
.
Attempt 1 (/bin/bash
, pass input as arguments
)
files=''
path=''
for f in "$@"
do
path=`dirname "$f"`
file=`basename "$f"`
files=$(printf '%s -C "%s" "%s"' "$files" "$path" "$file")
done
tar -cf ~/Desktop/archive.tar "$files"
Here I tried to just concat the filenames and pass them to tar
with the -C
flag, which is supposed to change to the provided directory. Probably overcomplicated.
Attempt 2 (/bin/bash
, pass input to stdin
)
tar -cf ~/Desktop/archive.tar -T -
This is working, but has a significant drawback: the full path gets saved to the archive (including my home dir name). Is there a way to make this only save the basename
and discard the path (which is what I was going for with Attempt 1)?
I'm open to go with either solution, if somebody can help me to get it to work.
Upvotes: 1
Views: 755
Reputation: 126108
Embedding quotes in the files
variable doesn't do what you expect (see BashFAQ #50). You need to use an array instead:
files=()
...
files+=(-C "$path" "$file")
...
tar -cf ~/Desktop/archive.tar "${files[@]}"
This'll execute something like:
tar -cf ~/Desktop/archive.tar -C "path1" "file1" -C "path2" "file2" ...
Upvotes: 2