Page 1 of 1

Automatically escape strings in BASH

Posted: Fri Oct 28, 2011 10:51 pm
by ^rooker
[PROBLEM]
If you're dealing with input strings in bash which contain special characters like spaces " ", brackets "(", etc... - it's necessary to escape those characters.

For example, if you'd try to call a script and pass it a string as argument which contains special characters, like this:
./myscript "my test file (1).txt"
it won't be enough to read it like this:

Code: Select all

FILENAME="$1"

[SOLUTION]

Code: Select all

FILENAME=$(printf '%q' "$1")
Now, $FILENAME will contain the escaped string as follows:
my\ test\ file\ \(1\).txt