Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Shell Execution in Ruby
# 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
@starkcoffee

This comment has been minimized.

Show comment Hide comment
@starkcoffee

starkcoffee Jun 14, 2012

awesome summary - thanks!

awesome summary - thanks!

@JosephPecoraro

This comment has been minimized.

Show comment Hide comment
@JosephPecoraro

JosephPecoraro Jun 14, 2012

Owner

JosephPecoraro commented Jun 14, 2012

@sivakumar-kailasam

This comment has been minimized.

Show comment Hide comment
@sivakumar-kailasam

sivakumar-kailasam Jun 17, 2012

Liked the extra advice :)

Liked the extra advice :)

@devilankur18

This comment has been minimized.

Show comment Hide comment
@devilankur18

devilankur18 Aug 24, 2012

Just Awsesome

Just Awsesome

@marksliva

This comment has been minimized.

Show comment Hide comment
@marksliva

marksliva Sep 18, 2013

Thank you!

Thank you!

@cizixs

This comment has been minimized.

Show comment Hide comment
@cizixs

cizixs Nov 15, 2013

Very useful , Thx!

cizixs commented Nov 15, 2013

Very useful , Thx!

@NeWbLt123

This comment has been minimized.

Show comment Hide comment
@NeWbLt123

NeWbLt123 Mar 21, 2014

Thanks, very helpful !

Thanks, very helpful !

@mx4492

This comment has been minimized.

Show comment Hide comment
@mx4492

mx4492 Apr 14, 2014

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

mx4492 commented Apr 14, 2014

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

@chrishough

This comment has been minimized.

Show comment Hide comment
@chrishough

chrishough Jun 5, 2014

thanks man!

thanks man!

@barbolo

This comment has been minimized.

Show comment Hide comment
@barbolo

barbolo Jun 12, 2015

I'd suggest you to check https://github.com/rtomayko/posix-spawn if you are having memory/latency issues when executing shell commands.

barbolo commented Jun 12, 2015

I'd suggest you to check https://github.com/rtomayko/posix-spawn if you are having memory/latency issues when executing shell commands.

@yanbit

This comment has been minimized.

Show comment Hide comment
@yanbit

yanbit Aug 14, 2015

thanks man!

yanbit commented Aug 14, 2015

thanks man!

@kassane

This comment has been minimized.

Show comment Hide comment
@kassane

kassane Aug 29, 2015

Awesome man!

kassane commented Aug 29, 2015

Awesome man!

@dminca

This comment has been minimized.

Show comment Hide comment
@dminca

dminca Sep 18, 2015

Thanks man, very interesting and useful 👍

dminca commented Sep 18, 2015

Thanks man, very interesting and useful 👍

@mika-cn

This comment has been minimized.

Show comment Hide comment
@mika-cn

mika-cn Dec 25, 2015

Awesome man! thanks

mika-cn commented Dec 25, 2015

Awesome man! thanks

@mkows

This comment has been minimized.

Show comment Hide comment
@mkows

mkows Jan 19, 2016

@JosephPecoraro thanks for sharing that! Any idea how to get rid of trailing "\n"?

$ cd /tmp
tmp$ irb
irb(main):001:0> `pwd`
=> "/tmp\n"
irb(main):002:0>  %x( pwd )
=> "/tmp\n"

One way to achieve this is:

`pwd`[0..-2]
=> "/tmp"

But I am wondering if there's nicer way to do it.

mkows commented Jan 19, 2016

@JosephPecoraro thanks for sharing that! Any idea how to get rid of trailing "\n"?

$ cd /tmp
tmp$ irb
irb(main):001:0> `pwd`
=> "/tmp\n"
irb(main):002:0>  %x( pwd )
=> "/tmp\n"

One way to achieve this is:

`pwd`[0..-2]
=> "/tmp"

But I am wondering if there's nicer way to do it.

@jerry-tao

This comment has been minimized.

Show comment Hide comment
@jerry-tao

jerry-tao Feb 10, 2016

@mkowaliszyn The backticks just simple redirect the stdout to the result. With the default way of backticks it won't get rid of \n for you.

You can just call strip to trim the \n.

Say

 `pwd`.strip.

With more than 1 line result you can:

`ls`.split("\n")

@mkowaliszyn The backticks just simple redirect the stdout to the result. With the default way of backticks it won't get rid of \n for you.

You can just call strip to trim the \n.

Say

 `pwd`.strip.

With more than 1 line result you can:

`ls`.split("\n")
@JosephPecoraro

This comment has been minimized.

Show comment Hide comment
@JosephPecoraro

JosephPecoraro Aug 12, 2016

@mkows late reply, but yes! String#chomp is a convenient method that exists for just such cases! It removes all trailing newlines from the string:

irb(main):001:0> `pwd`
=> "/tmp\n"
irb(main):002:0> `pwd`.chomp
=> "/tmp"

Very similar to strip / rstrip mention above.

Owner

JosephPecoraro commented Aug 12, 2016

@mkows late reply, but yes! String#chomp is a convenient method that exists for just such cases! It removes all trailing newlines from the string:

irb(main):001:0> `pwd`
=> "/tmp\n"
irb(main):002:0> `pwd`.chomp
=> "/tmp"

Very similar to strip / rstrip mention above.

@wellavelino

This comment has been minimized.

Show comment Hide comment
@wellavelino

wellavelino Nov 30, 2016

Thaaanks!

Thaaanks!

@diboanches

This comment has been minimized.

Show comment Hide comment
@diboanches

diboanches Apr 25, 2017

OSOM! Спасибо!

OSOM! Спасибо!

@ArtiusAstro

This comment has been minimized.

Show comment Hide comment
@ArtiusAstro

ArtiusAstro Sep 3, 2017

Awesome stuff!

Awesome stuff!

@Skalnark

This comment has been minimized.

Show comment Hide comment
@Skalnark

Skalnark Apr 7, 2018

Thanks!

Skalnark commented Apr 7, 2018

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment