Bash shell built-in function printf
has the format specifier %q
that will:
> quote the argument in a way that can be reused as shell input
Example (Bash shell):
printf '%q' "abc\ndef"
... will print:
abc\\ndef
Is there an equivalent format specifier for C's printf
?
C doesn't have any functions pertaining to bash or any other shell. Specifically, it doesn't have a builtin way to create a bash string literal that produces a given string.
It is, of course, possible to write such a function in C. A quick and dirty implementation of such a function would both prepend and append '
to the given string after replacing every instance of '
with '\''
.
That said, there are often better alternatives to generating shell code. Passing data to code/commands can be done using arguments, environment variables, pipes, files, etc.