How can I escape a double quote inside double quotes?

后端 未结 8 1493
庸人自扰
庸人自扰 2020-11-22 15:56

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         


        
8条回答
  •  无人及你
    2020-11-22 16:42

    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:

    $ echoI like to use"double quotes"sometimes

提交回复
热议问题