How to call function from shell script from ruby

244 Views Asked by At

How to call function in shell script from ruby (preferably using open3)

#!/bin/sh
# A simple script with a function...

function add()
{
  echo "1"
}

Ruby Script that does not work--

#!/apollo/bin/env ruby
# -*- ruby -*-   
require 'open3'
Open3.capture3('.\something.sh', 'add')
2

There are 2 best solutions below

0
Aleksei Matiushkin On BEST ANSWER

In the first place, you should have a valid bash function declaration.

Assuming something.sh was corrected to:

#!/bin/sh
# A simple script with a function...

bar () {
  echo "1"
}

You have to load it’s content into current shell and execute a function in it:

Open3.capture3(". ./something.sh && bar")
#⇒ ["1\n", "", #<Process::Status: pid 17113 exit 0>]
2
Mohammad Adnan On

For interest of others posting the answer. Basically, I end up doing work around like -

#!/apollo/bin/env ruby
# -*- ruby -*-   
require 'open3'

Open3.capture3(
    'bash',
    '-c',
    "source something.sh && add")

Basically Open3 (due to Ruby) fires every commands in different sessions and hence source of an script and method call should be done in single call.