Bash - 检查文件是否存在,文件名包含空格

时间:2017-12-13 07:55:32

标签: linux bash shell

我正在测试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表达式的具体问题

1 个答案:

答案 0 :(得分:7)

始终引用您的文件名,使用pip install PyInstaller==3.2.1来转义空格的想法是正确的,但是当与%q运算符一起使用时,不带引号的[会被拆分为多个单词$TFILE操作数在实际期望单个参数时接收太多参数。因此,一旦你引用它,就保留了空格,并在条件中传递了一个文字的单个参数。

-f

以上内容应该适用于任何POSIX兼容shell中的testFile="abc def ghi" printf -v quotedFile '%q' "$testFile" if [ -f "$quotedFile" ]; then printf 'My quoted file %s exists\n' "$quotedFile" fi )。但是,如果您仅针对[ shell定位脚本,则可以使用bash作为表达式进行评估时从不需要引用。所以你可以做到

[[

但总的来说,在file_with_spaces="abc def ghi" if [[ -f $file_with_spaces ]]; then printf 'My quoted file %s exists\n' "$file_with_spaces" fi 中为变量添加引号并不会有什么坏处。你总是可以做到。

相关问题