Loop through filenames with spaces within a path

半腔热情 提交于 2019-12-20 07:45:11

问题


I wanted to pass the path name to the script, but my path has spaces (eg. /Users/netto/iTunes \Media/Music/). I have tried putting the actual path directly on the for loop, and I was able to get all the files. Unfortunately, I could not pass it as variable. I have tried both double quote, and single quote. This is what I have currently

$PATH=$1
for f in $PATH; do
   echo "Processing file $f " 
done

Please let me know on how to do this. Thank you in advance.


回答1:


Spaces in variables are expanded at command level, so to solve the problem you can either put quotation marks around "$1" (so spaces are properly escaped) or use bash arrays.

Here is two example that should work:

 #!/bin/bash
DIR="$1"
for f in "$DIR"/* 
do
  echo "Processing file $f " 
done

or using bash arrays:

#!/bin/bash
FILES=("$1"*)
for f in "${FILES[@]}"
do
  echo "Processing file $f " 
done


来源:https://stackoverflow.com/questions/45301937/loop-through-filenames-with-spaces-within-a-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!