Check if a file exists with a filename containing spaces

后端 未结 1 585
慢半拍i
慢半拍i 2021-01-18 18:38

I am testing in Bash for if a file is existing, where the file name is escaped using $(printf \'%q\' \"$FNAME\").

This always produces an error using

相关标签:
1条回答
  • 2021-01-18 19:21

    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
    

    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
    

    But in general it doesn't hurt to add quotes to variables in bash. You can always do it.

    0 讨论(0)
提交回复
热议问题