ccca ccca - 5 months ago 14
Ruby Question

Ruby Executing Bash Commands on Linux

I am trying to write a ruby script to change my wireless mac address quickly by using "macchanger" tool.I have all the root permission to change it. And I try this:

`ifconfig #{@wifi_device.getName()} down`
output= `macchanger -m AA:BB:CC:DD:EE:FF #{@wifi_device.getName()}`
`ifconfig #{@wifi_device.getName()} up`

It usually works well , however when there is a problem , for example I enter an invalid mac address, and the bash prints any error , I can not catch it from Ruby.It prints only success messages , not errors. When I tried an invalid mac ,
My question if there is any suggestion to get rid of executing bash commands and read the output properly.


The shell needs to know where to send stderr. 2>&1 is a great way to do this it redirects 2(stderr) to 1(stdout) which is what "output" is capturing.

 output= `macchanger -m AA:BB:CC:DD:EE:FF #{@wifi_device.getName()} 2>&1`

The Advanced Bash Scripting Guide has a great chapter on I/O Redirection.