Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape filenames the same way Bash does it

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, and if I use exactly that "escaped" filename, it works.

For Instance:

An-Beat - Mentally Insine (Original Mix).mp3 => After bash Escapes It Using "TAB" An-Beat\ -\ Mentally\ Insine\ \(Original\ Mix\).mp3

I'm search for a function for bash that will escape a filename the same way "tab" escapes filenames.

like image 470
M.A.G Avatar asked Apr 09 '11 21:04

M.A.G


People also ask

How do you escape special characters in variable Bash?

Bash escape character is defined by non-quoted backslash (\). It preserves the literal value of the character followed by this symbol. Normally, $ symbol is used in bash to represent any defined variable.

What is the escape character in shell script?

The escape (\) preceding a character tells the shell to interpret that character literally. With certain commands and utilities, such as echo and sed, escaping a character may have the opposite effect - it can toggle on a special meaning for that character.

How do I escape a file in Linux?

About Escaping File PathsCharacters to be escaped include the backslash (\, because it is the escaping character) and the double quotes (").


1 Answers

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 
like image 186
sehe Avatar answered Sep 29 '22 13:09

sehe