printf %q should quote a string. However, when executed into a script, it deletes the spaces.
This command:
printf %q "hello world"
outputs:
hello\ world
which is correct.
This script:
#!/bin/bash
str="hello world"
printf %q $str
outputs:
helloworld
which is wrong.
If such behavior is indeed expected, what alternative exists in a script for quoting a string containing any character in a way that it can be translated back to the original by a called program?
Thanks.
Software: GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)
EDITED: Solved, thanks.
You should use:
Example:
When you run
printf %q $str, the shell expands it to:So, the strings
helloandworldare supplied as two separate arguments to theprintfcommand and it prints the two arguments side by side.But when you run
printf %q "$str", the shell expands it to:In this case, the string
hello worldis supplied as a single argument to theprintfcommand. This is what you want.Here is something you can experiment with to play with these concepts: