0

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
  }
}

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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?)

3 Comments

jq is a self-contained binary and easily installed, so "you don't have it" basically means "you have no write permissions to disk". What you've posted here is subject to all sorts of quoting issues, since any of the three arguments could themselves contain double quotes.
chepner – while I have full admin rights on my own machine, only sysadmins can install software on our servers and "you have no write permissions to disk" is commonplace on production systems. Yes — when I'm demonstrating a basic concept like a here-document I do not write production-ready code that handles quoting issues (or even spaces in filenames). I'm not a contractor writing code for Syirtblplmj, I'm just presenting another approach.
If you're on a production system, you don't use a hack like this: you get a proper tool installed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.