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
exec('ls')
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:
$?.pid
$?.exitstatus
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. If you're looking for more Ruby solutions to make your life easier, check out my book, pre-release version now available, Ruby For System Administrators. Click here to buy the pre-release where you can get 30+% discount, access to chapters as they're released, as well as an exclusive vote on content. If you found this helpful, subscribe to the mailing list to be notified of updates and when my book, Ruby For System Administrators, is released:
* indicates required