Scrivere un interprete di script in bash
Domanda
Ho scritto un wrapper bash a rubino che passa attraverso vari passaggi di installazione.
La versione più semplice è,
#!/bin/bash
# ruby_wrapper.sh
ruby
.
Ora voglio essere in grado di usare questo wrapper proprio come il normale rubino!Nello specifico, voglio creare un file .rb che utilizza questo "interprete".
#!/path/to/ruby_wrapper.sh
# my_file.rb
puts "hello world"
.
Quindi voglio essere in grado di fare $ ./my_file.rb
anziché $ ruby_wrapper.sh my_file.rb
è possibile?
The Documentazione reclami ISN 't.
.Si noti che l'interprete potrebbe non essere uno script di interprete.
Ma non vedo perché no.Qualcuno ha qualche idea per aggirare questo?
Soluzione
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).