3

We have a script running on our Debian server that grabs filenames in a directory and pushes them to our API. It runs fine when filenames don't have spaces. The usual answer to this common issue is to use double quotes around the variable name.

However, I can't find a tidy, brief and definitive solution for our particular case—code below. Although this answer has suggests changing the separator from space to \n, I'd rather get the double quote method right in our existing code.

Here's the relevant part of the code:

files=("$(ls $directory)") #$directory has the files we want to loop through

if [ ${#files[@]} -gt 0 ]; then
    getToken
    for i in $files
    do
        echo "$i"
        uploadFiles "$i"
    done
    exit
else
    echo "No files to upload"
    exit
fi
Community
  • 1
  • 1
Dave Everitt
  • 17,193
  • 6
  • 67
  • 97

1 Answers1

3

To handle files with whitespace in them, write your script as bellow:

shopt -s nullglob
files=("$directory"/*)

for i in "${files[@]}"
do  
  echo "$i"
  uploadFiles "$i"
done

Or if you don't need to keep the array, you can do

shopt -s nullglob

for i in "$directory"/*
do  
  echo "$i"
  uploadFiles "$i"
done
user000001
  • 32,226
  • 12
  • 81
  • 108
  • thanks - we only use the array once each time the script runs. It's running on a project critical cron job ATM so I'll try this as soon as we're able to stop/restart it and accept if all goes well. – Dave Everitt Sep 24 '15 at 19:17