1

contents of a.rb is :

if system("mount | grep /boot") != ""
  print "true"  # or do something
else 
  print "false" # or do something else 
end

Running this code doesn't print "true" or "false", but prints the output of system call.

]$ ruby a.rb 
/dev/sda1 on /boot type ext4 (rw)

What's the right syntax to check the if condition ?

iamauser
  • 11,119
  • 5
  • 34
  • 52

3 Answers3

6
if `mount | grep /boot` != ""
  print "true"  # or do something
else 
  print "false" # or do something else 
end
fl00r
  • 82,987
  • 33
  • 217
  • 237
1

In ruby, backticks cause the process to fork, which is expensive and slow. Instead, you could read /etc/mtab and look at the content which prevents forking.

if File.read('/etc/mtab').lines.grep(/boot/)[0]
  # not nil, its mounted
else
  # its nil, not mounted
end
Tom
  • 412
  • 2
  • 9
  • Hi, can you tell me what the 0 represents in the array index? – Vigneshwaran Aug 06 '15 at 13:16
  • 1
    See the ruby docs for Array#grep. When you grep an array, you get an array back. We're using grep to search the array (of lines from /etc/mtab) for "boot". If its found, it'll exist in the first element. – Tom Jul 04 '17 at 23:50
1

Don't use system calls, instead you can try this (fromFile path depends of your operating system, in RedHat is /proc/mounts):

fromFile='/proc/mounts'
toFind='/boot'
if File.readlines(fromFile).grep(toFind).size > 0
    print "true"  # or do something
else
    print "false" # or do something else 
end
Nacimota
  • 22,395
  • 6
  • 42
  • 44
Marc
  • 11
  • 1