Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
800 views
in Technique[技术] by (71.8m points)

bash - Loop through filenames with spaces within a path

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...