检查文件是否存在包含空格的文件名 [英] Check if a file exists with a filename containing spaces
问题描述
我正在Bash中测试文件是否存在,文件名使用$(printf '%q' "$FNAME")
进行转义.
I am testing in Bash for if a file is existing, where the file name is escaped using $(printf '%q' "$FNAME")
.
这总是使用if [ -f $FNAME ]
产生错误,如下面的注释示例所示.如何测试包含空格和其他字符的文件名?
This always produces an error using if [ -f $FNAME ]
as in the commented example below. How can I test for a filename that contains spaces and other characters?
#!/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
来转义空格的想法是正确的,但是与[
运算符一起使用时,未引用的$TFILE
拆分为多个单词,导致-f
操作数在实际上期望单个参数时接收太多参数.因此,一旦将其双引号括起来,就会保留空格,并在条件中传递一个字面量的单个参数.
Always quote your file-name, the idea of using %q
for escaping the spaces is right, but when used with the [
operator the unquoted $TFILE
is split into multiple words causing the -f
operand to receive too many arguments when it was actually expecting a single argument. So once you double-quote it, the white-spaces are preserved and a literal single argument is passed in the conditional.
testFile="abc def ghi"
printf -v quotedFile '%q' "$testFile"
if [ -f "$quotedFile" ]; then
printf 'My quoted file %s exists\n' "$quotedFile"
fi
以上内容在任何POSIX兼容shell中都应适用([
的用法).但是,如果仅针对bash
shell的脚本目标,则可以使用[[
,其中不再需要使用引号,因为它将其作为表达式进行评估.所以你可以做
the above should apply well (the usage of [
) in any POSIX compatible shells. But if you are targeting scripts for bash
shell alone, you can use the [[
in which quoting is never necessary as it evaluated as an expression. So you can just do
file_with_spaces="abc def ghi"
if [[ -f $file_with_spaces ]]; then
printf 'My quoted file %s exists\n' "$file_with_spaces"
fi
但是一般来说,在bash
中的变量中添加引号不会有什么坏处.您随时可以做到.
But in general it doesn't hurt to add quotes to variables in bash
. You can always do it.
这篇关于检查文件是否存在包含空格的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!