Parse NPM_TOKEN form .npmrc for a particular registry

Parse NPM_TOKEN form .npmrc for a particular registry

The .npmrc file has several entries like this:

//registry.npmjs.org/:_authToken=<sometoken>
//my.privateregistry.com/:_authToken=<sometoken>

Also there might be completely different entries in .npmrc.

How can I parse <sometoken> using a bash script for a particular registry by specifying its URL like registry.npmjs.org as a param for a bash script?

答案1

You could do it like this way:

#!/bin/bash

URLTOSEARCH="$1"
FILENAME="npmrc"

# you have to give an url
# so the search can begin
if [ -z "$URLTOSEARCH" ]; then
        echo "Please enter an url to search."
        exit 1
fi

# first, get the link
# out of the file
while read -r line
do
        # get the url
        EXTRACTEDURL=$(echo "$line" | grep -o '//.*/:' | sed 's/\/:/\//g')

        # get the token
        EXTRACTEDTOKEN=$(echo "$line" | grep -o '_authToken=.*' | sed 's/_authToken=//g')

        if [ "//$URLTOSEARCH/" == "$EXTRACTEDURL" ]; then
                echo "Token found: $EXTRACTEDTOKEN"
        fi
done < "$FILENAME"

相关内容