bashfilenamesspacedu

How to use a list of filenames with spaces in a variable to pass the contents of the variable as an argument to du?


I have a list of filenames in variable in my bash script. And I need to summarize disk usage of listed files. But I can't figure out how to escape spaces in file names. I tried various options, none of them worked.

It is a my test script:

#!/bin/bash

FILE_LIST="/tmp/filename_without_spaces
           /tmp/filename\ with\ spaces"

du -shc $FILE_LIST

FILE_LIST="/tmp/filename_without_spaces
           /tmp/filename\\ with\\ spaces"

du -shc $FILE_LIST

FILE_LIST="/tmp/filename_without_spaces
           \"/tmp/filename with spaces\""

du -shc $FILE_LIST

and the script output I got:

1,0G    /tmp/filename_without_spaces
du: cannot access '/tmp/filename\': No such file or directory
du: cannot access 'with\': No such file or directory
du: cannot access 'spaces': No such file or directory
1,0G    total
1,0G    /tmp/filename_without_spaces
du: cannot access '/tmp/filename\': No such file or directory
du: cannot access 'with\': No such file or directory
du: cannot access 'spaces': No such file or directory
1,0G    total
1,0G    /tmp/filename_without_spaces
du: cannot access '"/tmp/filename': No such file or directory
du: cannot access 'with': No such file or directory
du: cannot access 'spaces"': No such file or directory
1,0G    total

The file with spaces in name could not be processed by du.


Solution

  • Use bash arrays:

    #!/bin/bash
    
    file_list=( /tmp/filename_without_spaces '/tmp/filename with spaces' )    
    du -shc "${file_list[@]}"
    

    An array maps numbers to strings. Bash >= 4 also has associative arrays (maps strings to strings).
    http://mywiki.wooledge.org/BashSheet#Arrays
    http://mywiki.wooledge.org/BashFAQ/005
    http://wiki.bash-hackers.org/syntax/arrays