Serhii Shliakhov
Serhii Shliakhov

Reputation: 2770

How do I check that composer package installed in bash script

I'm trying to install composer package if it not installed in bash script. But now it doesn't work, and no_package function always pass

#!/bin/bash -e

no_package() {
    composer show | grep matchish/laravel-scout-elasticsearch | test
}

if [ no_package ]; then
  composer require "matchish/laravel-scout-elasticsearch"
else
  echo 'Package installed'
fi

UPD: Here is solution

package_installed() {
    composer show | grep matchish/laravel-scout-elasticsearch --quiet
}
if package_installed; then
  echo 'Package installed'
else
  composer require "matchish/laravel-scout-elasticsearch"
fi

Upvotes: 0

Views: 871

Answers (2)

Demarco Glover
Demarco Glover

Reputation: 27

I tested the test command, and I found that the test command returned the same result no matter what I piped in.

So it is better to run in this way

package_exist() {
    composer show | grep matchish/laravel-scout-elasticsearch >/dev/null
}

if package_exist; then
    echo 'installed'
else
    echo 'uninstalled'
    echo 'installing matchish/laravel-scout-elasticsearch'
    composer require "matchish/laravel-scout-elasticsearch"
fi

Upvotes: 1

l0b0
l0b0

Reputation: 58808

There are two misunderstandings here:

  1. You can't pipe stuff to test.
  2. if some_command is the way to do something if a command succeeds. [ no_package ] doesn't actually run the command, it simply checks that the string "no_package" is not empty and therefore always succeeds.

In addition to this you may want to use the --quiet flag to grep to avoid printing the package name.

Upvotes: 1

Related Questions