0

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/deploy@1.2.3.0" // 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?
jizzer
  • 11
  • 2
  • You're missing the input for the `grep` command. You have extra square brackets. – Barmar Oct 07 '22 at 17:53
  • I think you're a bit confused about what `[ ]` does. My answer [here](https://stackoverflow.com/questions/49849957/bash-conditional-based-on-exit-code-of-command/49850110) might help. – Gordon Davisson Oct 07 '22 at 21:19

1 Answers1

1

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks for the answer. Just to make sure, why is it not "==" but "="? I thought in bash, equal operator is "=="? – jizzer Oct 07 '22 at 18:03
  • That's a bash extension, standard is `=` – Barmar Oct 07 '22 at 18:06
  • @jizzer It depends on the context (shell syntax is *extremely* context-dependent). In a `[ ]` test or `[[ ]]` conditional expression, `=` is the standard string-equality operator (but bash allows `==` as a nonstandard alternative), and `-eq` is numeric equality. In a `(( ))` or `$(( ))` arithmetic expression, `==` is numeric equality, and `=` is assignment (and there is no string comparison operator, because it's an arithmetic context). – Gordon Davisson Oct 07 '22 at 21:17