Suppressing the output of a command run using 'system' method while running it in a ruby script

后端 未结 8 1218
醉梦人生
醉梦人生 2020-12-29 20:13

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 mea

8条回答
  •  囚心锁ツ
    2020-12-29 20:46

    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
    

提交回复
热议问题