在 ruby 脚本中运行时使用“系统"方法抑制命令运行的输出 [英] Suppressing the output of a command run using 'system' method while running it in a ruby script
问题描述
我不确定这是否有意义,但我在想是否有办法在使用 ruby 中的 system
方法运行时抑制命令显示的输出?我的意思是它应该只向 STDOUT 输出 true 或 false 而不是命令的输出.我认为只有当命令可以静默运行而不是从 system
方法时才能完成.有人可以提供更多见解吗?
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?
推荐答案
在调用 system
后,退出代码位于特殊变量 $?
中,因此如果 >useradd
返回不同的值以指示用户是否已成功添加(例如 0 表示成功),然后您可以执行以下操作:
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
重定向到 /dev/null
将抑制输出.
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
这篇关于在 ruby 脚本中运行时使用“系统"方法抑制命令运行的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!