简体   繁体   中英

Writing an script interpreter in bash

I wrote a bash wrapper to ruby that goes through various setup steps.

The most basic version is,

   #!/bin/bash 
   #   ruby_wrapper.sh
   ruby

Now I want to be able to use this wrapper just like regular ruby! Specifically, I want to create a .rb file that uses this "interpreter".

   #!/path/to/ruby_wrapper.sh
   #  my_file.rb
   puts "hello world"

So I want to be able to do $ ./my_file.rb instead of $ ruby_wrapper.sh my_file.rb

Is this possible?

The documentation claims it isn't.

Note that the interpreter may not itself be an interpreter script.

But I don't see why not. Does anyone have any ideas to get around this?

Try invoking your wrapper with /usr/bin/env . It's actually good practice to execute Ruby scripts with /usr/bin/env ruby as you don't have to hard code the path to the ruby binary, so this is not unnatural.

$ cat ruby_wrapper.sh 
#!/bin/bash
exec ruby "$@"

$ cat wrapped.rb 
#!/usr/bin/env /tmp/ruby_wrapper.sh
puts "hello world"

$ ./wrapped.rb 
hello world

Also as a side note see how I've used exec in the wrapper script. This will allow the ruby interpreter to take over your wrapper script's process rather than run as a child process of your script. This makes the wrapper transparent to the caller (signals will be delivered directly to ruby rather than to bash, for example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM