파일이있는 경우 파일이 존재하고 파일 이름이 $ (printf '% q' "$ FNAME") 으로 항상 이스케이프 처리됩니다. 아래의 주석 된 예와 같이 [-f $ FNAME] 인 경우 을 사용하여 오류가 발생합니다. 공백과 다른 문자가 포함 된 파일 이름을 테스트하려면 어떻게해야합니까?Bash - 파일 이름에 공백이있는 파일이 있는지 확인하십시오.
#!/usr/bin/env bash
# code used in Raspberry Pi Podcasting Jukebox project
# youtube-dl -f 17 --get-filename https://www.youtube.com/watch?v=AgkM5g_Ob-w
# returns "HOW ABUNDANCE WILL CHANGE THE WORLD - Elon Musk 2017-AgkM5g_Ob-w.3gp"
# Purpose: To test if file exists before downloading
# for testing purposes using an existing regular file "abc def ghi"
AFILE="abc def ghi"
TFILE=$(printf '%q' "$AFILE") # Escaping filename using printf
echo $TFILE # returns abc\ def\ ghi
# if [ -f $AFILE ] # this test returns false every time with error [:too many arguments
if [ -f $TFILE ] # This test also returns FALSE with err [: too many arguments
then
echo "Existing"
# don't download
else
echo "Not existing"
# youtube-dl http://www.youtube.com/watch?v=AgkM5g_Ob-w
fi
편집 :이 질문에 대한 해결책은 항상 파일 이름, 탈출을 위해 %q
을 사용하는 아이디어를 인용 [[]]
[공백이있는 배시 및 파일 이름] 가능한 복제본 (https://stackoverflow.com/questions/1574898/bash-and-filenames-with-spaces) –
예, 비슷한 질문이지만 공백이있는 배쉬 및 파일 이름 ] (https://stackoverflow.com/questions/1574898/bash-and-filenames-with-spaces)에는 테스트를 Bash에서 [[]]을 통해 표현식을 작성하는 특정 문제에 대한 해결책이 포함되어 있지 않습니다. – casperl