0

This question already has an answer here:

I would like to escape path with white space which works fine when I use it directly like this:

$ printf '%q' "/path/to/first dir/dir/"
/path/to/first\ dir/dir/

When I use a variable instead of string though the return is a string with no white space whatsoever:

$ testpath="/path/to/first dir/dir/" && printf '%q' $testpath
/path/to/firstdir/dir/

Is there any way to escape white space in a path with printf and a variable. Or any other simple solution without using awk/sed/regex?

marked as duplicate by αғsнιη, Christopher, Jeff Schaller, roaima, Timothy Martin Mar 24 '18 at 0:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

You need to quote the variable

testpath="/path/to/first dir/dir/" && printf '%q' "$testpath"
  • I could swear I tested this. But it seems like I didn't, because quoting works. – monkeywrench Mar 23 '18 at 13:26
1
testpath="/path/to/first dir/dir/"
printf '%q' "$testpath"

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

Not the answer you're looking for? Browse other questions tagged or ask your own question.