如何在Bash脚本中使用双引号处理文件名中的空格 [英] How to handle spaces in filenames using double quotes in a Bash script

查看:191
本文介绍了如何在Bash脚本中使用双引号处理文件名中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在Debian服务器上运行了一个脚本,该脚本抓取目录中的文件名并将其推送到我们的API.当文件名没有空格时,它运行良好.对于这个常见问题,通常的答案是在变量名周围使用双引号.

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.

但是,对于我们的特殊情况,我找不到一个整洁,简短而确定的解决方案-下面的代码.尽管此答案建议将分隔符从空格更改为\n,但我还是想在其中使用双引号方法我们现有的代码.

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

推荐答案

要处理其中包含空格的文件,请将脚本编写如下:

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

这篇关于如何在Bash脚本中使用双引号处理文件名中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆