How to Escape File Names in Bash Shell Scripts

Sun 29 March 2009 Category: Linux

After fighting with Bash for quite some time, I found out that the following code provides a nice basis for escaping special characters. Ofcource it is not complete, but the most important characters are filtered.

If anybody has a better solution, please let me know. It works and it is readable but not pretty.

FILE_ESCAPED=`echo "$FILE" | \

sed s/\ /\\\\\\\ /g | \

sed s/\'/\\\\\\\'/g | \

sed s/\&/\\\\\\\&/g | \

sed s/\;/\\\\\\\;/g | \

sed s/(/\\\\\(/g | \

sed s/)/\\\\\)/g `