Alex D.
Alex D.

Reputation: 79

How to make a Ruby file (in a gem) executable from anywhere like a regular command?

I have a command in my gem: bin/tennis. Currently to execute it you have to cd into the gem and run bin/tennis. I was wondering is it possible to make it work like a regular shell command? i.e able to run it from any dir.

Upvotes: 4

Views: 696

Answers (1)

casraf
casraf

Reputation: 21694

Anything that is globally executable, lies under one of the directories in the $PATH variable (%PATH% on Windows).

For example, $PATH may look like this:

$ echo $PATH
/usr/local/opt/rbenv/shims:/Users/casraf/bin:/Users/casraf/bin:/usr/local/heroku/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/opt/fzf/bin

You may add directories to this list, separating with :, and each of these paths will be looked into when executing a command globally.

So you could either:

  1. Save a copy of the executable in the gem exec dir:

    ln -s /your/bin/file $(ruby -rubygems -e 'puts Gem.dir')

    This will create a symbolic link to your bin, inside the regular gem executable dir (it should already be in your $PATH, if not, just add it:

    export PATH=$(ruby -rubygems -e 'puts Gem.dir'):$PATH

    You can put this in your .bashrc or .bash_profile to make sure it happens on every terminal session (if you have a non-standard setup, you may need to find another file to put this in)

  2. Or just add the regular path to your PATH variable:

    PATH=/path/to/gem/bin:$PATH

Upvotes: 1

Related Questions