Calling Bash Commands From Ruby *

Question

How do I call console/bash commands from inside of a Ruby Program? Also, how do I get output from these commands back into my program?

Answer

This explanation is based on this commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link.

Ways to execute a shell script

cmd = "echo 'hi'" # Sample string that can be used

1. Kernel#`, commonly called backticks – `cmd`

This is like many other languages, including Bash, PHP, and Perl

Returns the result of the shell command

Docs: http://ruby-doc.org/core/Kernel.html#method-i-60

value = `echo 'hi'`
value = `#{cmd}`

2. Built-in syntax, %x( cmd )

Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{ ... } is allowed.

Returns the result of the shell command, just like the backticks

Docs: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html

value = %x( echo 'hi' )
value = %x[ #{cmd} ]

3. Kernel#system

Executes the given command in a subshell,

Return: true if the command was found and ran successfully, false otherwise

Docs: http://ruby-doc.org/core/Kernel.html#method-i-system

wasGood = system( "echo 'hi'" )
wasGood = system( cmd )

4. Kernel#exec

Replaces the current process by running the given external command.

Return: none, the current process is replaced and never continues

Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec

exec( "echo 'hi'" )
exec( cmd ) # Note: this will never be reached beacuse of the line above

Extra Advice

$?, which is the same as $CHILD_STATUS, accesses the status of the last system executed command if you use the backticks, system() or %{}. You can then access the exitstatus and pid properties

$?.exitstatus

More Reading

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/2232/" >Calling Bash Commands From Ruby< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment