akiva
akiva

Reputation: 2737

escaped filename slashes

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.

Upvotes: 0

Views: 2110

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

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:

$ file='some file name.txt'
$ touch "$file"
$ ls "$file"
some file name.txt

If you insist, though, use the %q format with printf:

$ str='The great theater'
$ printf '%q\n' "$str"
The\ great\ theater
$ escaped=$(printf '%q' "$str")
$ echo "$escaped"
The\ great\ theater

Note that this won't escape slashes as they aren't normally special characters.

Upvotes: 5

Related Questions