How to Escape File Names in Bash Shell Scripts

March 29, 2009 Category: Bash

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 `

Comments