I have bash script my_tar.sh
which calls tar czf output.tgz
on 3 files with filename spaces passed from array: file
, file 2
and file 3
.
#!/bin/bash
declare -a files_to_zip
files_to_zip+=(\'file\')
files_to_zip+=(\'file 2\')
files_to_zip+=(\'file 3\')
echo "tar czf output.tgz "${files_to_zip[*]}""
tar czf output.tgz "${files_to_zip[*]}" || echo "ERROR"
Though three files exist, when tar
is ran inside the script, it ends with error. However when I literally run echo
output (which is the same as next command of my_tar.sh
) inside bash console, tar
runs ok:
$ ls
file file 2 file 3 my_tar.sh
$ ./my_tar.sh
tar czf output.tgz 'file' 'file 2' 'file 3'
tar: 'file' 'file 2' 'file 3': Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
ERROR
$ tar czf output.tgz 'file' 'file 2' 'file 3'
$
Any ideas?
The problem is, that you escape the '
and thereby add it to the file name instead of using it to quote the string:
files_to_zip+=(\'file 2\')
vs
files_to_zip+=( 'file 2' )
Also, it generally is advisable to use @
instead of the asterisk (*
) to reference all array elements, since the asterisk will not be interpreted when quoted (-> http://tldp.org/LDP/abs/html/arrays.html, Example 27-7) .
Also also I assume your intention was to put quotes in the string when printing out the array elements. To do so, you need to escape the quotes.
echo "tar czf output.tgz \"${files_to_zip[@]}\""
Your fixed script would look like
#!/bin/bash
declare -a files_to_zip
files_to_zip+=( 'file' )
files_to_zip+=( 'file 2' )
files_to_zip+=( 'file 3' )
echo "tar czf output.tgz \"${files_to_zip[@]}\""
tar czf output.tgz "${files_to_zip[@]}" || echo "ERROR"