Skip to content

Instantly share code, notes, and snippets.

@coreyja
Last active April 29, 2022 14:43
Show Gist options
  • Save coreyja/7bf81a89d1565f7ba79642785a2ab153 to your computer and use it in GitHub Desktop.
Save coreyja/7bf81a89d1565f7ba79642785a2ab153 to your computer and use it in GitHub Desktop.
Bash and Ruby Nerd Snipe

I got nerd sniped on Twitter!

Originally the prompt was to do the installing of the interpretter in the shebang, but I was able to fit it all in one file and that felt close enough.

#!/usr/bin/env RBENV_VERSION=3.1.2 HAHA=ruby bash
## Our first hack is right over here ^^^^
## The ruby cli won't run a file with a shebang, UNLESS the shebang
## contains the string 'ruby' somewhere in it. Here we are using it as the value
## of the HAHA environment variable. This is enough to get Ruby to run the file.
## The next line is doing double duty! It needs to be valid Ruby AND Bash
## In Ruby this is going to start a multiline comment (which will end at the `=end` below)
## In Bash this is going to create a `=begin` function that no-ops. [We won't ever call this function]
=begin () { :; }
## Now we are in a Ruby comment, and still executing normal Bash. So the following only needs to be valid Bash
## Let's make sure Ruby is installed. We'll do that via `rbenv` and `ruby-build`
set -e
export PATH="$HOME/.rbenv/bin:$PATH"
if ! hash rbenv 2> /dev/null; then
mkdir -p ~/.rbenv
curl -L https://github.com/rbenv/rbenv/tarball/master | tar -xz -C ~/.rbenv --strip-components=1
mkdir -p ~/.rbenv/plugins/ruby-build
curl -L https://github.com/rbenv/ruby-build/tarball/master | tar -xz -C ~/.rbenv/plugins/ruby-build --strip-components=1
fi
eval "$(rbenv init - bash)"
rbenv install $RBENV_VERSION --skip-existing
## Now that we have Ruby installed at the version we specified, lets run our script in Ruby! We capture the exit code to return
ruby $(which $0)
exit $?
## After ^^ the Bash script exits, so we no longer need to be valid Bash!
=end
## We are out of our Multiline comment, and all done with Bash, so now we can proceed with the Ruby script
def hello(name:)
puts "Hello #{name}. We are running Ruby #{RUBY_VERSION}"
end
name = "World"
## And _finally_ we are ready to use some new Ruby 3.1 syntax!
hello(name:)
#!/usr/bin/env RBENV_VERSION=3.1.2 HAHA=ruby bash
=begin () { :; }
export PATH="$HOME/.rbenv/bin:$PATH"
if ! hash rbenv 2> /dev/null; then
mkdir -p ~/.rbenv; curl -L https://github.com/rbenv/rbenv/tarball/master | tar -xz -C ~/.rbenv --strip-components=1
mkdir -p ~/.rbenv/plugins/ruby-build
curl -L https://github.com/rbenv/ruby-build/tarball/master | tar -xz -C ~/.rbenv/plugins/ruby-build --strip-components=1
fi
eval "$(rbenv init - bash)"; rbenv install $RBENV_VERSION -s; ruby $(which $0); exit $?
=end
def hello(name:)
puts "Hello #{name}. We are running Ruby #{RUBY_VERSION}"
end
name = "World"
hello(name:)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment