madh
madh

Reputation: 648

Autocomplete for the ruby command in bash

In the Bash shell, I would like to run a directory of ruby scripts from anywhere. Adding the directory to the $PATH doesn't do it.

I want to type 'ruby,' start typing the first letters of a script name, and then press tab to autocomplete the script name.

For instance, I'm in /~/username/foo/bar and want to run /~/ruby/test/script1.rb

~/username/foo/bar $ ruby scri

press tab and

/username/foo/bar $ ruby script1.rb

appears. And then I'd be able to press enter and have the script run, even though I'm not in the right directory.

Is this possible?

Upvotes: 1

Views: 1330

Answers (5)

Eric G
Eric G

Reputation: 1292

I found this tutorial was helpful in particular. Basically you want to get to this line:

COMPREPLY=( $(compgen -W "${files}" -- ${cur}) )

Then the main thing you have to figure out how to do is get the list of files in the current dir + files in your /~/ruby/test dir, and assign this to files.

Although it's a little more complicated because you have to take into account the path.

Upvotes: 1

Jamie
Jamie

Reputation: 2265

If you add this to the top line of you scripts. Use 'which ruby' to find out where your interpreter is located and use that path instead.

#!/usr/local/bin/ruby -w

Then change them to be executable with

chmod +x ruby_script.rb

You'll be able to ruby them like any normal program, for example (although you may want to lose the .rb extension)

ruby_script.rb

Upvotes: 2

OscarRyz
OscarRyz

Reputation: 199334

Why don't you just make your ruby executable and include the interpreter in the first line as in:

$cat >un.rb<<END
> #!/usr/bin/ruby
> puts "Hi"
> END
$chmod +x un.rb 
$export PATH=$PATH:/Users/oscarreyes
$cd /tmp 
$un.rb 
Hi

I've used tab to autocomplete my command un.rb

Upvotes: 0

ChristopheD
ChristopheD

Reputation: 116287

Have a look at the /etc/bash_completion file and the complete command. Googling these keywords should yield you some tutorials as how to customize bash autocompletion.

Also make sure your ruby scripts have a correct she-bang line.

Upvotes: 2

Topher Fangio
Topher Fangio

Reputation: 20687

As far as I know, the only bash completion that you can do is running the script itself. If you were to make the script executable and put it in your path, you should be able to simply run the script by typing

my_scri

and then hitting tab. This would probably be the easiest method. What OS are you on? We might be able to help a bit more.

Upvotes: 1

Related Questions