Cannot tar array of files with spaces inside filename inside bash script

I have bash script which calls tar czf output.tgz on 3 files with filename spaces passed from array: file, file 2 and file 3.


declare -a files_to_zip

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 inside bash console, tar runs ok:

$ ls
file  file 2  file 3
$ ./
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
$ 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\')


    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 (->, 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

    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"