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?

0

2 Answers 2

4

You need to quote the variable

testpath="/path/to/first dir/dir/" && printf '%q' "$testpath"
1
  • I could swear I tested this. But it seems like I didn't, because quoting works. Commented Mar 23, 2018 at 13:26
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.