Automatically escape strings in BASH

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

Automatically escape strings in BASH

Post 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
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
Post Reply