22

I realize this might be a dumb question but I have a Centos-7 minimal server install and the "which" command does not exist or is missing. I have a script that needs it and I cannot find out what the yum package is that installs it. The code is below and is from a make file.

which grep > /dev/null 2> /dev/null

if test "$?" != "0"
then
    echo "\"grep\" command not found."
    echo "Installation is aborted."
    exit 1
fi

Any help would be appreciated... this is difficult if not impossible to google

Machavity
  • 30,841
  • 27
  • 92
  • 100
asgard
  • 223
  • 1
  • 2
  • 4
  • Is `grep` or `which` missing? – Odi Jan 07 '15 at 08:44
  • As an aside, your code has several bugs. You want simply `if ! type -p grep >/dev/null 2>&1; then echo "grep not found, installation aborted" >&2; fi` – tripleee Jun 09 '19 at 08:09
  • Very much not dumb; I was a bit surprised that `make` and `which` were missing from my centos7 experience, so thank you for asking. @Wintermute's answer was educational for me. – jgreve Sep 24 '19 at 20:29

2 Answers2

33

To find a package in CentOS, use yum whatprovides:

yum whatprovides *bin/which

In this particular case, the package is called which, so

yum install which

should pull it in.

Wintermute
  • 42,983
  • 5
  • 77
  • 80
9

Instead of which command you can use type command.

type grep > /dev/null 2> /dev/null
if test "$?" != "0"
then
    echo "\"grep\" command not found."
    echo "Installation is aborted."
    exit 1
fi
Sriharsha Kalluru
  • 1,743
  • 3
  • 21
  • 27
  • 2
    This is the better solution. `which` is nonportable, while `type` is mandated by POSIX and built into the shell. – tripleee Jan 07 '15 at 09:22
  • 3
    And `type -P grep` output path to `grep`, exactly what `which` does. – Étienne Bersac Apr 17 '19 at 08:20
  • The roundabout explicit examintion of `$?` is still unidiomatic and clumsy. The *purpose* of `if` and friends is to run a command and examine its exit status; you should almost never need to explicitly check if `$?` is non-zero. Anything which looks like `cmd; if [ $? -ne 0 ]` is better written `if ! cmd` – tripleee Jun 09 '19 at 08:12
  • how do you get `type` to output _only_ the location of the command? I very commonly want to do `cat $(which ansible)` for example, to inspect python script contents. – AlanSE Dec 20 '19 at 15:36