Reputation: 17876
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.
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
Upvotes: 3
Views: 2275
Reputation: 33327
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
Upvotes: 3