Skip to content

Instantly share code, notes, and snippets.

@sambacha
Forked from DarrenN/get-npm-package-version
Last active October 7, 2020 07:15
Show Gist options
  • Save sambacha/cb1f28b7d350937f0a0dafa43313e56c to your computer and use it in GitHub Desktop.
Save sambacha/cb1f28b7d350937f0a0dafa43313e56c to your computer and use it in GitHub Desktop.
Extract version from package.json (NPM) using bash / shell

No need for sed or grep here. I solved the issue in a deploy script with

awk '/version/{gsub(/("|",)/,"",$2);print $2};' package.json

here's a stupid but fun way w/o awk or sed

grep version package.json | cut -c 15- | rev | cut -c 3- | rev

Cheers

PACKAGE_VERSION=$(grep -m1 version package.json | awk -F: '{ print $2 }' | sed 's/[", ]//g')

or if you have jq:

PACKAGE_VERSION=$(jq -r ".name" package.json)
"vars": "env | grep npm_package_"

PACKAGE_VERSION=$(node -p -e "require('./package.json').version")
```bash

```bash
VERSION=$(npm version patch)
VERSION=$(echo $VERSION | cut -c 2-)
    "postpublish" : "PACKAGE_VERSION=$(cat package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[\",]//g' | tr -d '[[:space:]]') && git tag $PACKAGE_VERSION && git push --tags"
PACKAGE_VERSION=$(cat package.json \
    | grep version \
    | head -1 \
    | awk -F: '{ print $2 }' \
    | sed 's/[",]//g' \
    | tr -d '[[:space:]]')

echo $PACKAGE_VERSION
# Version key/value should be on his own line
PACKAGE_VERSION=$(cat package.json \
| grep version \
| head -1 \
| awk -F: '{ print $2 }' \
| sed 's/[",]//g')
echo $PACKAGE_VERSION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment