我在
Bash中测试是否存在文件,其中文件名使用$(printf’%q’“$FNAME”)进行转义
如下面的注释示例所示,使用if [-f $FNAME]时总会产生错误.如何测试包含空格和其他字符的文件名?
#!/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
编辑:这个问题的解决方案涉及通过[[]]使测试条件成为Bash表达式的具体问题