Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extract version from package.json (NPM) using bash / shell
# 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' \
| tr -d '[[:space:]]')
echo $PACKAGE_VERSION
@yvele

This comment has been minimized.

Copy link
Owner Author

commented Feb 17, 2016

Updated to trim white spaces. Thanks to @swissmanu and @dbaba 👌

@4F2E4A2E

This comment has been minimized.

Copy link

commented Apr 14, 2017

# Gitlab CI working version
PACKAGE_VERSION=$(cat package.json | grep version | head -1 | awk -F= "{ print $2 }" | sed 's/[version:,\",]//g' | tr -d '[[:space:]]')
@syahiaoui

This comment has been minimized.

Copy link

commented May 25, 2018

variables:
PACKAGE_VERSION: $(cat package.json | grep version | head -1 | awk -F= "{ print $2 }" | sed 's/[version:,\",]//g' | tr -d '[[:space:]]')

//in your job or template
.package-template: &package_template
image: docker-hub.registry.integ.fr.auchan.com/docker:latest
stage: package
tags:
- stocks
script:
- export VERSION=eval $PACKAGE_VERSION
- echo "======> Getting VERSION: $VERSION"

@hejmsdz

This comment has been minimized.

Copy link

commented Jun 5, 2019

PACKAGE_VERSION=$(grep '"version":' package.json -m1 | cut -d\" -f4)
@melarts

This comment has been minimized.

Copy link

commented Oct 9, 2019

If I may, if fixed the regex for sed because per example if my package version was : v6.0.0-dev.3, I would get 6.0.0-d.3 as a result because "version" was not targeted as a full word.
And I had to add -E for the regex pipe to be understood

My change :

PACKAGE_VERSION=$(cat package.json | grep version | head -1 | awk -F= "{ print $2 }" | sed -E 's/(version)|[:,\",]//g' | tr -d '[[:space:]]')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.