Escape filenames the same way Bash does it

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

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.


$ 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

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 \$.


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...'