When I use the \"tab\" key in bash
(when you have started to type the filename and you want it to complete), bash
escapes the filename correctly, a
$ string="An-Beat - Mentally Insine (Original Mix).mp3"
$ echo ${string// /\\ }
An-Beat\ -\ Mentally\ Insine\ (Original\ Mix).mp3
$ string=${string// /\\ }
$ echo ${string//(/\\( }
An-Beat - Mentally Insine \( Original Mix).mp3
I may be a little late to the party but what worked for me is:
ls --quoting-style=shell-escape
This way it also escapes characters like !
or '
.
Use printf
(1):
x='a real \good %* load of c$rap'
x=$(printf '%q' "$x")
echo $x
will return
a\ real\ \\good\ %\*\ load\ of\ c\$rap
The solution from "sehe" works fine, in addition, you can also use double quotes (") instead of single apostrophe (') to by able to use variables:
x="a real \good %* load of crap from ${USER}"
echo $(printf '%q' "$x")
Of course the string may not contain $ or " itself or you have to escape those manulally by splash \$.
I'm going to elaborate on sehe's response on this one.
If you want to pass the argument to be converted as a shell script parameter, encase the parameter in "'s.
#!/bin/bash
x=$(printf '%q' "$1")
echo $x
I really like the printf solution, since it does every special character, just like bash.
ls --quoting-style=escape /somedir
this will output the escaped filenames, and also work with unicode characters, printf method does not work with Chinese, it outputs something like $'\206\305...'