jakethedog
jakethedog

Reputation: 350

using bash variable with quotes, ignores filenames with quotes

I run a simple bash script that requires double quotes around a multi-part command like so:

for i in /data/*; do 
    mycommand "first_directive ; second_directive $i"
done

To handle special characters, I put the quotes around the variable so it looks like this: "first_directive ; second_directive '$i'" which works for the most part, but I found an edge case.

When a filename contains two single quotes, as in there_are_12''_in_a_foot it ignores the '' and just looks for there_are_12_in_a_foot

Here is the content of the data folder:

$ ls /data/
what_do_they_call_a_quarter_pounder
they_use_the_metric_system
there_are_12''_in_a_foot

I've tried every combination of quotes I can think of, and searching of course, but I can't find anything that works.

Upvotes: 1

Views: 117

Answers (2)

hek2mgl
hek2mgl

Reputation: 157967

You may use:

'${variable//\'/\'\\\'\'}'

instead of

'$variable'

That will escape the single quotes like this:

'there_are_12'\'''\''_in_a_foot'

May because it depends on my_command of course.

Upvotes: 1

gaderian
gaderian

Reputation: 1

You should be able to escape the ' with a backslash.

there_are_12\'\'_in_a_foot

Upvotes: 0

Related Questions