tags:

views:

100

answers:

2

I am not sure if this makes sense but I am thinking if there is a way to suppress the output shown for a command when run using the system method in ruby? I mean it should just output true or false to STDOUT and not the output of the command. What I think is it can just only be done if the command can run silently and not from the system method. Can someone provide a bit more insight?

Thanks.

A: 

You can also use backticks or %x

Azeem.Butt
yes but I will not be able to use it as a condition to execute a few statements which I can do when using 'system'
kilari
That makes very little sense so maybe you should post an actual example.
Azeem.Butt
if system('useradd xx')p "User added successfully"elsep "User seems to exit"endkinda above. If I use backticks or %x it will always return true so the condition is of no use.
kilari
So write a different conditional that actually parses the output and might be a better idea than what you have now.
Azeem.Butt
ok thanks, checking the exit status is working for me.
kilari
+1  A: 

After a call to system the exit code is in the special variable $? so if useradd returns different values to indicate if the user was successfully added (e.g. 0 for success) then you can do the following:

system('useradd xx > /dev/null')
if $? == 0
  puts 'added'
else
  puts 'failed'
end

where the redirect to /dev/null will suppress the output.

Alternatively if the program being called does not use its exit code to indicate success or failure you can use backticks and search for a particular substring in the output e.g.

if `useradd xx`.include? 'success'
  puts 'it worked'
else
  puts 'failed to add user'
end
mikej
checking the exit status seems to work perfect.Thanks.
kilari