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
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.