jizzer
jizzer

Reputation: 11

Assign npm output as a variable in bash and using if condition

Objective: Iterate through a list of package and only publish the package which does not exist in the npm registry. If the package with same version is already in the registry, discard any further action.

package="@react-framework/[email protected]" // package name extracted from the actual tgz file

checkRegistry=$(npm view $package) # There are three types of output
# NPM Err (Package Not Exists)
# NULL (Package Not Exists)
# return information about the package (Package Exists)

if [ [grep -q "npm ERR!"] || [$checkRegistry==""] ]; then
   npm publish $package
 

I am keep having an error around the if-statement, and assuming there is a syntax error with my condition.

I would like to know if:

  1. Is it possible to assign an output from a npm command (in this case npm view) to a variable?
  2. Is there anything wrong with the syntax from the if-statement?

Upvotes: 0

Views: 299

Answers (1)

Barmar
Barmar

Reputation: 780869

grep shouldn't be inside square brackets, since you want to test its success directly, not use its output in a test command.

You're also not using the value of $checkRegistry as the input to the grep command.

But if you just want to check if $checkRegistry matches a pattern, you don't need to use grep, you can use the shell's built-in regexp matching.

if [[ "$checkRegistry" = "" || "$checkRegistry" =~ "npm ERR!" ]]
then
    npm publish "$package"
fi

Upvotes: 1

Related Questions