How can I escape double quotes inside a double string in Bash?
For example, in my shell script
#!/bin/bash
dbload=\"load data local infile \\\"\'gfp
Bash allows you to place strings adjacently, and they'll just end up being glued together.
So this:
$ echo "Hello"', world!'
produces
Hello, world!
The trick is to alternate between single and double-quoted strings as required. Unfortunately, it quickly gets very messy. For example:
$ echo "I like to use" '"double quotes"' "sometimes"
produces
I like to use "double quotes" sometimes
In your example, I would do it something like this:
$ dbtable=example
$ dbload='load data local infile "'"'gfpoint.csv'"'" into '"table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"'"'"' LINES "'TERMINATED BY "'"'\n'"'" IGNORE 1 LINES'
$ echo $dbload
which produces the following output:
load data local infile "'gfpoint.csv'" into table example FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "'\n'" IGNORE 1 LINES
It's difficult to see what's going on here, but I can annotate it using Unicode quotes. The following won't work in bash – it's just for illustration:
dbload=
‘load data local infile "
’“'gfpoint.csv'
”‘" into
’“table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '
”‘"
’“' LINES
”‘TERMINATED BY "
’“'\n'
”‘" IGNORE 1 LINES
’
The quotes like “ ‘ ’ ” in the above will be interpreted by bash. The quotes like " '
will end up in the resulting variable.
If I give the same treatment to the earlier example, it looks like this:
$ echo
“I like to use
”‘
"double quotes"
’“
sometimes
”