0

I want to echo a variable with spaces into a text file.

a=a\ b\ c
echo $a > /tmp/a

The above results in a file with a b c in it. What if I need the file to read a\ b\ c?

I've tried printf %q $a but that doesn't seem to do what I want either.

Note: Also assume that I don't produce the content of $a it is passed to me outside my control. I just need to make sure it is saved with escaped spaces.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

3 Answers3

3

Backslashes escape the next character; in your case, you've escaped the space, at which point the contents of $a become: a b c. If you want the contents of $a to have backslashes, then you need to escape them:

a=a\\\ b\\\ c

or

a='a\ b\ c'

If $a already contains text with spaces and you want to save it to a file, simply:

printf "%q" "$a" > /tmp/a

When you ran:

printf "%q" $a > /tmp/a

You told printf to quote 3 split & globbed pieces of text: a, b, and c, which it dutifully escaped (doing nothing) before being redirected into /tmp/a as abc.

Take a good read through: Why does my shell script choke on whitespace or other special characters? to see what's going on.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • What if I want to convert a variable where spaces aren't escaped to one where they are? For example $a is simply random text but it needs to be saved with escaped spaces? Should I run grep and replace spaces with \? – Philip Kirkbride Nov 21 '17 at 16:03
  • Maybe something like echo $a | tr ' ' '\ ' > /tmp/a? – Philip Kirkbride Nov 21 '17 at 16:12
1

Just put it in quotes.

a="a\ b\ c"

Alternatively, escape the escape.

a=a\\\ b\\\ c

Both end up with the same result.

1

Solution based on feedback from Jeff:

echo $a | sed -e "s/ /\\\ /g" > /tmp/a