Build a JSON string with Bash variables

后端 未结 12 1394
感情败类
感情败类 2020-11-29 01:57

I need to read these bash variables into my JSON string and I am not familiar with bash. any help is appreciated.

#!/bin/sh

BUCKET_NAME=testbucket
OBJECT_N         


        
12条回答
  •  渐次进展
    2020-11-29 02:38

    To build upon Hao's answer using NodeJS: you can split up the lines, and use the -p option which saves having to use console.log.

    JSON_STRING=$(node -pe "
      JSON.stringify({
        bucketname: process.env.BUCKET_NAME,
        objectname: process.env.OBJECT_NAME,
        targetlocation: process.env.TARGET_LOCATION
      });
    ")
    

    An inconvenience is that you need to export the variables beforehand, i.e.

    export BUCKET_NAME=testbucket
    # etc.
    

    Note: You might be thinking, why use process.env? Why not just use single quotes and have bucketname: '$BUCKET_NAME', etc so bash inserts the variables? The reason is that using process.env is safer - if you don't have control over the contents of $TARGET_LOCATION it could inject JavaScript into your node command and do malicious things (by closing the single quote, e.g. the $TARGET_LOCATION string contents could be '}); /* Here I can run commands to delete files! */; console.log({'a': 'b. On the other hand, process.env takes care of sanitising the input.

提交回复
热议问题