I want to generate filename from a user-inputed string and to make sure that it is safely escaped.
for example, if the user enters /usr/bash the output will be \/usr\/bash
and if the input is The great theater the output is The\ great\ theater.
Are you sure you need to do this? This is kind of a code smell. There’s very likely a better way to do whatever you’re trying to do than mangling your input. Properly quoting your variables when you use them usually suffices:
If you insist, though, use the
%qformat with printf:Note that this won’t escape slashes as they aren’t normally special characters.