34

How can I check if a program exists within a fish script?

I know that there is no absolute solution with Bash, but using if type PROGRAM >/dev/null 2>&1; then... gave good results.

Is there something similar with fish?

azmeuk
  • 4,026
  • 3
  • 37
  • 64

1 Answers1

65

There is type -q, as in

if type -q $program
     # do stuff
end

which returns 0 if something is a function, builtin or external program (i.e. if it is something fish will execute).

There is also

  • command -q, which will return 0 only if it exists as an external program
  • builtin -q, which will return 0 only if it is a fish builtin
  • functions -q, which will return 0 only if it is a fish function

For all of these the "-q" flag silences all output and just queries for existence.

If e.g. builtin -q returns true, that just means it is also a builtin - it can still be a function or command as well.

command -q works since fish 3.1.0 because the -q flag implies -s, before it would have to be command -sq.

faho
  • 14,470
  • 2
  • 37
  • 47
  • Hiya faho, is this the correct way to check multiple executables in path: `if type -q tldr; and type -q peco; tldr $argv | peco; end;` Or is there a better way? Maybe to do it all in one go e.g. `type -q tldr peco` (the docs do say we can specify multiple names for `type` but it does not fail when I try it that it returns true e.g. `type -q aaa bbb; and echo true` it doesn't print anything as expected but `if type -q aaa bbb; echo true; end` does print `true`. So what's up? – user14492 Jul 16 '21 at 12:14
  • 1
    `type -q` returns true when *at least one* of the arguments exists - `type -q type slartibartfast` will succeed everywhere because `type` always exists. So yes, you will have to check separately. – faho Jul 16 '21 at 14:28