Search code examples
bashstring-formatting

bash string formatting within a quote


I’m trying to generalize a command inside a bash script but I’m stuck with some string formatting. The code I’m trying to recreate (which works)

curl -X POST -H 'Content-Type: application/json' $CLUSTER -d '{
      "source" : "s3://blah/part-00004-9d2ba62f-496e-4cfd-9001-f40f0e33e927-c000.csv",
      "format" : "csv"
    }'

with the below command (which doesn’t work)

filename='part-00004-9d2ba62f-496e-4cfd-9001-f40f0e33e927-c000.csv'
curl -X POST -H 'Content-Type: application/json' $CLUSTER -d '{
    "source" : "s3://blah/$filename",
    "format" : "csv"
    }'

I also tried out the tip from Expansion of variables inside single quotes in a command in Bash but it didn’t pan out.

"source" : '"s3://blah/$filename"',

Any ideas?


Solution

  • Try this (see the "'"):

    filename='part-00004-9d2ba62f-496e-4cfd-9001-f40f0e33e927-c000.csv'
    curl -X POST -H 'Content-Type: application/json' $CLUSTER -d '{
        "source" : "'"s3://blah/$filename"'",
        "format" : "csv"
        }'
    

    The first "'" is "double quote symbol for the -d argument, switch single quote escaping off, start double quote escaping". The second "'" is similar.