Check if file exists with file name containing spaces

I am testing in Bash whether there exists a file where the file name is escaped using $(printf '%q' "$FNAME") .

This always results in an error using if [ -f $FNAME ] , as in the example with comments below. How to check the name of a file containing 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 
+5
source share
1 answer

Always include your file name, the idea of ​​using %q to escape spaces is correct, but when used with the [ unspecified $TFILE breaks into a few words, causing the -f operand to get too many arguments when it really expects one argument. Therefore, when you specify it twice, white spaces are preserved and a literal single argument is passed in the conditional expression.

 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 be well applied (using [ ) in any POSIX compatible shells. But if you target scripts only for the bash , you can use [[ , in which quoting is never required since it is evaluated as an expression. Therefore 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 this.

+8
source

Source: https://habr.com/ru/post/1274023/


All Articles