public
Last active

Shell Execution in Ruby

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
# Ways to execute a shell script in Ruby
# Example Script - Joseph Pecoraro
 
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/classes/Kernel.html#M001111
 
value = `echo 'hi'` # or uglier but valid => Kernel.`("echo 'hi'")
value = `#{cmd}` # or uglier but valid => Kernel.`("#{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/classes/Kernel.html#M002992
 
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/classes/Kernel.html#M002992
 
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 (if you require 'english')
# Accesses the status of the last system executed command if
# you use the backticks, system() or %x{}.
# You can then access the ``exitstatus'' and ``pid'' properties
 
$?.exitstatus
 
# More Reading
# http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands
# http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html

awesome summary - thanks!

Heh, thanks. I still refer back to it every couple of months :)

Cheers,

  • Joe

Sent from my iPhone

On Jun 14, 2012, at 1:14 PM, Duana Saskia Stanley reply@reply.github.com wrote:

awesome summary - thanks!


Reply to this email directly or view it on GitHub:
https://gist.github.com/4069

Liked the extra advice :)

Very useful , Thx!

Thanks, very helpful !

In case you need to drop the ball when the command fails, https://github.com/mx4492/simple_cmd

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.