I am trying to create an application which will have a different result on Debian based system with dpkg package manager, Arch based system with pacman package manager and Redhat based system with yum package manager or rpm package manager.
To detect the system, I am using Kernel#system
method primarily there.
Nevertheless this works:
%x(which pacman) # => "/usr/bin/pacman\n"
%x(which dpkg) # => ""
system('which pacman') # => true # and perhaps better to redirect stdout to /dev/null
system('which dpkg') # => false
But I don't like to use which
because it's not a builtin. That said, your package manager can remove which
(pacman -R which
) or you may be missing which.
In that case, I would love to use type -p
In BASH or sh:
$ type -p pacman
/usr/bin/pacman
$ echo $?
0
$ type -p dpkg
$ echo $?
1
But in Ruby:
> system('type -p pacman')
# => nil
> system('type -p dpkg')
# => nil
> %x('type -p pacman')
sh: type -p pacman: command not found
# => ""
# OR
> require 'open3'
# => true
> Open3.capture2e('type -p pacman')
Traceback (most recent call last):
7: from /home/sourav/.irb:350:in `<main>'
6: from (irb):7
5: from (irb):7:in `rescue in irb_binding'
4: from /usr/lib/ruby/2.6.0/open3.rb:390:in `capture2e'
3: from /usr/lib/ruby/2.6.0/open3.rb:208:in `popen2e'
2: from /usr/lib/ruby/2.6.0/open3.rb:213:in `popen_run'
1: from /usr/lib/ruby/2.6.0/open3.rb:213:in `spawn'
Errno::ENOENT (No such file or directory - type)
> IO.popen('type -p pacman')
Traceback (most recent call last):
4: from /home/sourav/.irb:350:in `<main>'
3: from (irb):6
2: from (irb):6:in `rescue in irb_binding'
1: from (irb):6:in `popen'
Errno::ENOENT (No such file or directory - type)
Same goes with PTY#spawn
, exec
, Kernel#
``
How can I use the type -p
command in Ruby?
Try running your command by first spawning a new shell:
system('sh -c "type -p pry"')
/Users/foo/.rvm/gems/ruby-2.6.3/bin/pry
=> true
And likewise get false
when it isn't found:
system('sh -c "type -p qwertyasdf"')
=> false