尝试使用Ruby中的if / else检查变量的内容

时间:2017-03-30 17:57:12

标签: ruby linux

我使用以下代码检查进程是否正在使用ps和grep运行并将PID存储在变量中。

然后我用if / else语句检查该变量中是否有值。目标是如果条件为真则在if块中运行什么,如果不是,则执行else中的内容

fisheye_pid = `ps -ef | grep fisheyeboot | grep -v grep | awk '{print $2}'`
kill_fisheye = `kill #{fisheye_pid}`

if "#{fisheye_pid}" != nil or 0
  puts ''
  puts  '--------------------'
  puts '|  Stopping Fisheye  |'
  puts  '--------------------'
  puts kill_fisheye
  sleep(5)
    if "#{fisheye_pid}" == nil or 0
      puts 'Fisheye has been stopped..'
      puts ''
    end
else
  puts 'Fisheye is not running, proceeding.'

end

如果有任何问题,请告诉我。它可能是我想要的小东西。

1 个答案:

答案 0 :(得分:1)

杀死进程“fisheyeboot”

fisheye_pid = `ps -ef | grep fisheyeboot | grep -v grep | awk '{print $2}'`.to_i

if fisheye_pid > 0
  puts ''
  puts  '--------------------'
  puts '|  Stopping Fisheye  |'
  puts  '--------------------'
  `kill #{fisheye_pid}`
  # TODO: sleep 5 seconds and recheck process by running "ps" again
else
  puts 'Fisheye is not running, proceeding.'
end

你也可以使用killall并丢弃输出:

`killall fisheyeboot`