2

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?

2 Answers2

4

You need to quote the variable

testpath="/path/to/first dir/dir/" && printf '%q' "$testpath"
nohillside
  • 3,251
3
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