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 
1

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.