G. Deward
G. Deward

Reputation: 1592

How to retrieve JSON value in BASH (automatic version in git commit)?

How can I retrieve the version attribute from the following json file AND use it in a BASH script?..

file package.json

{
  "name": "myapp",
  "version": "0.0.1"
}

desired script: bpush.sh

#!/bin/bash
gulp bump
git add -A
eval $pkg_ver = getjson('./package.json', 'version')
git commit -a -m "$pkg_ver"
git push origin master

Obviously, the getjson() function is invalid. That is what I'm trying to figure out.

Edit: Final Result
Here's what I used, thanks to the folks below...

#!/bin/sh

pkg_ver=$(jq '.version' package.json)
pkg_ver=${pkg_ver//\"/}
git add -A
git commit -a -m $pkg_ver
git push origin master

Upvotes: 3

Views: 2408

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185025

Why not using itself from a here-doc ? :)

Remember, JS stands for JavaScript Object Notation

pkg_ver=$(
    node<<EOF
    var obj = $(<package.json);
    console.log(obj.version);
EOF
)

Replace node by the nodejs executable or if you don't have node

Or as a one-liner :

node <<< "var obj = $(<package.json); console.log(obj.version);"

Upvotes: 4

vsminkov
vsminkov

Reputation: 11250

You can use also python one-liner

pkg_ver=$(
    python -c 'import sys,json; print(json.load(sys.stdin)["version"])' \
    < package.json
)

or even

pkg_ver=$(
    python -c 'import sys,json;print(json.load(open("package.json"))["version"])'
)

Upvotes: 1

dbosky
dbosky

Reputation: 1641

If your json file is more complex then I would suggest to use jq - link

pkg_ver=$(jq '.version' package.json)

However, if you have only this two items then maybe using sed, awk or tr would be easier.

Upvotes: 6

Related Questions