Home > database >  Create a JSON file with parameters from a shell script
Create a JSON file with parameters from a shell script

Time:12-02

Let's say that with a bash script I want to create a file, so to the command to create the file will be something like this:

myscript hostgroup_one 2

hostgroup_one and the number 2 are parameters.

How can I insert the parameters in the lines below and output all the lines as a file?

{
  "bool": {
    "should": [
      {
        "match_phrase": {
          "hostgroup.keyword": "$1"
        }
      }
    ],
    "minimum_should_match": $2
  }
}

CodePudding user response:

I'd use to build the JSON:

jq  -n \
    --arg hostgroup "$1" \
    --argjson minimum "$2" \
    '{bool: {should: [{match_phrase: {"hostgroup.keyword": $hostgroup}}], minimum_should_match: $minimum}}'

will produce your desired output.

CodePudding user response:

While jq is a great tool for manipulating json, as glenn jackman recommends, if you don't have it and your sysadmin won't install it (?!?)...
You can use a "here document"

Your myscript could look something like this:

#!/bin/bash
echo "dollar-1 is '${1}' dollar-2 is '${2}' dollar-3 is '${3}'"
cat <<EOF >"${1}"
{
  "bool": {
    "should": [
      {
        "match_phrase": {
          "hostgroup.keyword": "${2}"
        }
      }
    ],
    "minimum_should_match": ${3}
  }
}
EOF
echo "done"

I've made the output filename the first parameter, and then your two parameters, so it would be run like:
myscript output.json hostgroup_one 2

You don't need to do that, you could use 2 params and redirect output:
myscript hostgroup_one 2 > output.json

(note you don't have to use EOF as your here-document delimiter, I just like it)

Of course you don't need the echo statements, and you should have error checking (does ${#} equal 3 parameters?)

  • Related