Bash 스크립트에서 공백이 있는 파일/폴더 처리

Bash 스크립트에서 공백이 있는 파일/폴더 처리

폴더 이름에 공백이 있을 수 있는 시스템에서 place.sqlite를 검색해야 합니다. 폴더 이름에 공백 없이 작동합니다.

    for each in `find /home/ -name "places.sqlite" | grep -i ".mozilla/firefox"` ;do
         echo "${each}"
    done

다음을 인쇄합니다: /home/itsupport/.mozilla/firefox/d2gigsya.default/places.sqlite (예:)

그러나 폴더에 공백이 포함되어 있으면 파일 경로가 잘리고 스크립트가 중단됩니다!

요약하면 다음 유형의 폴더가 스크립트에서 작동합니다.

    $ sudo find /home/ -name "places.sqlite" | grep -i ".mozilla/firefox"
    /home/itsupport/.mozilla/firefox/d2gigsya.default/places.sqlite

그리고 공백이 있는 이 폴더는 스크립트에서 작동하지 않습니다.

    $ sudo find /home/ -name "places.sqlite" | grep -i ".mozilla/firefox"
    /home/itsupport/.mozilla/firefox/Random Ass Location/places.sqlite

$(command) 등을 사용할 수 있다는 것을 알고 있지만 find를 루프 변수로 사용할 때 무엇을 해야 할지 잘 모르겠습니다. 어쩌면 그게 내 실수일 수도 있다. 어쨌든 어떤 도움이라도 좋을 것입니다.

답변1

find-print0이 문제를 처리할 플래그가 있습니다 .

#!/bin/bash

find . -print0 | while read -d $'\0' file
do
    echo ${file}
done

예:

$ ls
script.sh  space name
$ ./script.sh 
.
./script.sh
./space name

답변2

또 다른 옵션은 공백 문자 대신 IFS를 사용하여 줄 끝에서 분할하는 것입니다.

oldIFS="$IFS"
IFS=$'\n'
for bla in ....
do
...
done
IFS="$oldIFS" # restoring to avoid surprising the rest of the script

답변3

파일은 잘 알려진 위치에 있으므로 다음을 사용할 수 있습니다.

for each in /home/*/.mozilla/firefox/*/places.sqlite
do echo "${each}"
done

관련 정보