Loading...

Friday, October 3, 2008

Using Shell Commands in Ruby

The following is a step by step guide how can you write shell linux commands inside ruby code and get their results in customized output created by ruby.


First of all execute the following command on shell prompt

shell> vi userinfo.rb

This will open up vi editor with a file named userinfo opened in it

1. Press i on your keyboard, this will switch the file userinfo into insert mode
2. Write the following code in it



#Code Starts
def user
user = `users`
end

def groups
groups = `groups`
end

puts "You are #{user} and you belongs to the groups \n #{groups}"
#Code Ends

3. Press ESC key on your keyboard to exit insert mode
4. Now write :wq and press enter key on your keyboard

This will throw you out to the shell prompt. On the shell prompt write the following command

shell> ruby userinfo.rb

You will get the customized output like this

You are root and you belong to the groups
  [A list of group will be displayed on this line]

Thats it to executing shell linux commands inside your linux code

Go back to the table of contents for 'Ruby on Linux'

1 comment:

brainmeasure2010 said...

Thanks for your informative blog.your command seems to be very interesting.
Six Sigma Certification

Free Advertising