简体   繁体   中英

How to handle spaces in filenames using double quotes in a Bash script

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM