arraysbashunixscripting

Bash array with spaces in elements


I'm trying to construct an array in bash of the filenames from my camera:

FILES=(2011-09-04 21.43.02.jpg
2011-09-05 10.23.14.jpg
2011-09-09 12.31.16.jpg
2011-09-11 08.43.12.jpg)

As you can see, there is a space in the middle of each filename.

I've tried wrapping each name in quotes, and escaping the space with a backslash, neither of which works.

When I try to access the array elements, it continues to treat the space as the element delimiter.

How can I properly capture the filenames with a space inside the name?


Solution

  • I think the issue might be partly with how you're accessing the elements. If I do a simple for elem in $FILES, I experience the same issue as you. However, if I access the array through its indices, like so, it works if I add the elements either numerically or with escapes:

    for ((i = 0; i < ${#FILES[@]}; i++))
    do
        echo "${FILES[$i]}"
    done
    

    Any of these declarations of $FILES should work:

    FILES=(2011-09-04\ 21.43.02.jpg
    2011-09-05\ 10.23.14.jpg
    2011-09-09\ 12.31.16.jpg
    2011-09-11\ 08.43.12.jpg)
    

    or

    FILES=("2011-09-04 21.43.02.jpg"
    "2011-09-05 10.23.14.jpg"
    "2011-09-09 12.31.16.jpg"
    "2011-09-11 08.43.12.jpg")
    

    or

    FILES[0]="2011-09-04 21.43.02.jpg"
    FILES[1]="2011-09-05 10.23.14.jpg"
    FILES[2]="2011-09-09 12.31.16.jpg"
    FILES[3]="2011-09-11 08.43.12.jpg"