I would like to print the contents of a variable in such a way, that the printed output could be pasted directly into a shell to get the original content of the variable.
This is trivial if the content doesn't contain any special characters, esp no quotes. e.g.
$ x=foo
$ echo x=${x}
x=foo
In the above example i can take the output (x=foo
and paste it into a new terminal to assign foo
to x
).
If the variable content contains spaces, things get a bit trickier, but it's still easy:
$ x="foo bar"
$ echo x=\"${x}\"
x="foo bar"
Now trouble starts, if the variable is allowed to contain any character, e.g.:
$ x=foo\"bar\'baz
$echo ${x}
foo"bar'baz
$ echo x=\"${x}\"
x="foo"bar'baz"
$ x="foo"bar'baz"
>
(and the terminal hangs, waiting for me to close the unbalanced "
)
What I would have expected was an output like the following:
x=foo\"bar\'baz
How would I do that, preferably POSIX compliant (but if it cannot be helped, bash only)?