开发者

Run linux command in ruby [duplicate]

开发者 https://www.devze.com 2023-02-09 17:48 出处:网络
This question already has answers here: How to call shell commands from Ruby (22 answers) Closed 2 years ago.
This question already has answers here: How to call shell commands from Ruby (22 answers) Closed 2 years ago. 开发者_StackOverflow社区

I'm trying to do the following..

   if "ps | grep -e file" then
      true;
   else
      false;

What would I need to do to make the string n the if statement execute the linux command listed?


Simply use system("command"). It'll return true if the command was successfully executed.

EDIT Just read your question again, and I believe that what you're looking for is this:

if `ps | grep -e file`.empty? # no matches
  true
else
  false
end


Don't have to call grep. Just call ps and let Ruby find the things you want.

if `ps`["file"]
  ...
else
  ...
end


Linux ps has a -C switch to check for a specific program name:

if "ps -C file" then
   true;
else
   false;

however - if you have a construct like

if (predicate) then true; else false; 

it should be the same as

(predicate) 


You can run your Linux Command like this

`echo "done"`

This will print done as output.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号