Execute Shell Commands in Ruby

Execute Shell Commands in Ruby

  1. Use Backticks (`) to Execute Shell Commands in Ruby
  2. Use %x to Execute Shell Commands in Ruby
  3. Use the system Method to Execute Shell Commands in Ruby
  4. Use the exec Method to Execute Shell Commands in Ruby

This article will introduce the various methods to call shell commands in a Ruby program.

Use Backticks (`) to Execute Shell Commands in Ruby

Example code:

puts `echo 'Hello World'`

Output:

Hello World

Use %x to Execute Shell Commands in Ruby

Example code:

puts %x( echo 'Hello World' )

Output:

Hello World

Use the system Method to Execute Shell Commands in Ruby

Example code:

system "echo 'Hello World'"

Output:

Hello World

There’s no need to use puts in this example because the method already outputs the result of the command.

Use the exec Method to Execute Shell Commands in Ruby

Example code:

exec "echo 'Hello World'"

Output:

Hello World

This also works like the previous example, no need for the puts method.