Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking a bash command in a if statement in Ruby

Tags:

ruby

How can I check the return value (true/false) of bash command in an if statement in Ruby. I want something like this to work,

if ("/usr/bin/fs wscell > /dev/null 2>&1")
                has_afs = "true"
        else
                has_afs = "false"
        end

It complains with the following error meaning, it will always return true.

 (irb):5: warning: string literal in condition

What's the correct syntax ?

UPDATE :

 /usr/bin/fs wscell 

looks for afs installed and running condition. It will throw a string like this,

 This workstation belongs to cell <afs_server_name>

If afs is not running, the command exits with status 1

like image 939
iamauser Avatar asked Apr 03 '13 18:04

iamauser


People also ask

How to do if statements bash?

Bash if Statement Example In the script, add the following lines: echo -n "Please enter a whole number: " read VAR echo Your number is $VAR if test $VAR -gt 100 then echo "It's greater than 100" fi echo Bye!

How do you write if else in one line Ruby?

In Ruby, the condition and the then part of an if expression must be separated by either an expression separator (i.e. ; or a newline) or the then keyword. There is also a conditional operator in Ruby, but that is completely unnecessary.


2 Answers

You want backticks rather than double-quotes. To check a program's output:

has_afs = `/usr/bin/fs wscell > /dev/null 2>&1` == SOMETHING ? 'true' : 'false'

Where SOMETHING is filled in with what you're looking for.

like image 195
Chuck Avatar answered Oct 24 '22 20:10

Chuck


You should probably use system() or Backticks and then check the exit status of the command ($?.exitstatus):

Heres a good quicktip read: http://rubyquicktips.com/post/5862861056/execute-shell-commands)

UPDATE:

system("/usr/bin/fs wscell > /dev/null 2>&1")  # Returns false if command failed
has_afs = $?.exitstatus != 1  # Check if afs is running
like image 33
gonz Avatar answered Oct 24 '22 20:10

gonz