0

I want to find all programs with name like "gcc", "gcc-4.2", "gcc-4.9" and so on.

To find all binaries I tried with which -a gcc*.

But "*" is not recognized as 'any' with which command.

Is there way to find all programs in PATH environment variable by pattern match?

  • 2
    In most shells you can simply type gcc and press Tab twice to have it autocompleted. Does that work for you or what else is your situation? Meaning, why would you need this? – slhck Aug 31 '13 at 6:52
  • 1
    In UNIX and Linux, * is expanded before the program is executed. That means the interpretation does not depend on the program. In this case, gcc* is expanded in the current directory. That's why it doesn't work. – MSalters Aug 31 '13 at 6:59
  • In OSX default gcc is llvm based that is placed /usr/bin/gcc. and by using brew installed gcc is placed /usr/local/bin/gcc-4.x. I wanted to know there are other gcc-* programs. Of course I can use find, but it takes some time. – ironsand Aug 31 '13 at 7:04
  • Thanks MSalters! I was not clear about that point. I thought it depends on programs. – ironsand Aug 31 '13 at 7:07
  • 1
    If you are just looking for the ones in your $PATH, the easiest way is to hit tab twice as @slhck suggested. – terdon Aug 31 '13 at 14:06
4

There is a BASH built-in command compgen which can be used to list all commands, functions, aliases and built-ins.

compgen -abck | grep "gcc"

Parameters: help compgen

compgen:
[-abcdefgjksuv] 
[-o option]
[-A action]
[-G globpat]
[-W wordlist]
[-F function]
[-C command]
[-X filterpat]
[-P prefix]
[-S suffix]
[word]
2

Here is a quick and dirty sample script to do what you want in practice:

#!/bin/sh
IFS=:
for i in $PATH; do
    for j in "$i"/$1; do
        [ -f "$j" ] && [ -x "$j" ] && printf '%s\n' "$j"
    done
done

Save this as e.g. whichglob and make it executable. Sample run:

$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ ./whichglob grep*
/usr/bin/grepdiff
/usr/bin/grep-excuses
/usr/bin/grepjar
/bin/grep

Actually all the functionality in which (-a, exit statuses, multiple file match inputs) can be easily added in this shell script context as well, but I leave that as an exercise for the reader.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.