Running Bash Commands From Ruby

Whenever we talk about Ruby and System Administration, its only a matter of time before Bash is mentioned.  There are several different ways to run a bash script or command in Ruby.  Which one you pick will be based on what you want to occur, full control changed to the Bash command,  check of the command success, etc. Here are a few different ways: Backticks This is the easiest and quickest way to run a command and will look familiar to perl users. Simply enclose the command you want to run in backtacks like so:
current_directory_contents = `ls`
current_directory_contents = `#{command}`
Backticks work thanks to the Kernel module, whose methods are available in every Ruby object.  See further backtick documentation here. %x method This method is same as the backtick method, but allows you specify your delimiters, most commonly a pair of ' ' " "  ( ) [ ] { }or < > but non paired, repeated delimiters such as $ are also valid such as:
current_directory_contents = %x('ls')
current_directory_contents = %x$'ls'$
current_directory_contents = %x{ #{command} }
exec This is the least common and least useful method of running external command as exec replaces the current process (your Ruby script) with the exec'd process.  So continuing our previous example
would simply list the contents of the current directory and drop you back to your shell, not ideal.  If you'd like to see more about exec, its also in Kernel. system If you want to explicitly check if the command ran successfully, you can use the system command.  Unlike the backtick or %x method, system will execute the command and return true if the command was successful (Exit status of 0) or false if it was unsuccessful (Exit status of anything else).
did_it_run_ok = system('ls')
Special Variables Another perl-ism that carries over to Ruby is the use of special variables.  All of these commands allow you to retrieve the PID and exit status of the previously run command:
These are all the ways to launch external commands in Ruby using the Kernel module.   There are more using the IO module and we'll cover them at a later date.
## Complementary Process Diagnostic With 30 minutes spent looking over your existing pipeline or process, we can diagnose the root cause(s) of slow releases or bugs. After 30 minutes on the phone or Skype with me, you will: 1. Understand why your existing process may be allowing bugs to reach production and slow you down 1. Learn ways you can increase the speed that features reach customers 1. Have a list of ideas for improving your release process We’ll have to move fast, of course, to get through all this in 30 minutes but don’t worry, I’ll keep us on track. To receive your meeting agenda and scheduling instructions, enter your email address below and click the button.