How to send commands to the ruby interpreter from a Shell Script?

Asked

Viewed 174 times

1

This is more out of curiosity... I’ve seen some examples of what I want to do, but in Perl. I tried to find a way to do the same in Ruby, but to no avail.

I want a function to generate an MD5 hash from a passed word as argument. The intention is to send this argument to the ruby interpreter, and then use the return in the function. I made a "pseudo-code" to illustrate what I want:

function generate_hash {
  # Enviar o argumento para o interpretador e obter o retorno.
  ruby "Digest::MD5.hexdigest($1)"
}

Does anyone have any idea how I could make this integration?

  • This is vulnerable to code injection through the variable $1.

  • Yes, @Matheusmoreira. I did. But like I said, it’s just a curiosity I had. If I were to use that, it would be for very punctual things.

2 answers

1


To execute a direct command in the Ruby interpreter use -e, in short your example would be:

#!/bin/bash
function generate_hash {
  # Enviar o argumento para o interpretador e obter o retorno.
  ruby -e "require 'digest/md5';puts Digest::MD5.hexdigest('$1')"
}
generate_hash $1

Upshot:

⟩ ./test.sh a
0cc175b9c0f1b6a831c399e269772661
  • 2

    ruby -r digest/md5 -e "puts Digest::MD5.hexdigest '$1'"

1

A great way is to use I/O to send the data. In bash:

generate_hash() {
  ruby -r digest/md5 -e 'puts Digest::MD5.hexdigest STDIN.read'
}

echo 'argumento' | generate_hash
generate_hash < arquivo
  • Very interesting. What struck me most in its solution was the possibility of using the pipe.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.