【发布时间】:2017-12-13 07:55:31
【问题描述】:
我正在 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 and filenames with spaces 不包含通过 [[ ]] 使测试条件成为 Bash 中的表达式的具体问题的解决方案