完全披露:我真的不懂Ruby。我大部分都在假装它。
我想用一个脚本来收集Casper中的库存,我用它来管理一堆Mac。我正在尝试将变量传递给带有%x
的shell命令。问题是,Ruby正在将变量视为注释。以下是相关代码:
def get_host
host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
raise Error, "this machine must not be bound to AD.\n try again." if host == nil
end
def get_ou
host = get_host
dsout = %x(/usr/bin/dscl /Search -read /Computers/#{host}).to_a
ou = dsout.select {|item| item =~ /OU=/}.to_s.split(",")[1].to_s.gsub(/OU=/, '').chomp
end
我尝试使用后退刻度而不是%x
,但得到了相同的结果。该命令应返回有关其运行的主机的大量信息,而是返回dscl /Search -read /Computers
的结果,该结果始终为name: dsRecTypeStandard:Computers
。
我怎样才能完成我想做的事?
答案 0 :(得分:5)
问题出在这里。 Ruby总是返回方法中的最后一个表达式。
def get_host
host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
raise Error, "this machine must not be bound to AD.\n try again." if host == nil
end
在这种情况下,最后一个表达式为:
raise Error, "this machine must not be bound to AD.\n try again." if host == nil
如果raise
,它将返回host == nil
(实际上不会发生)的返回值,如果nil
将返回host != nil
。因此,您的方法永远不会返回nil
之外的其他内容。替换为:
def get_host
host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
raise Error, "this machine must not be bound to AD.\n try again." if host == nil
host
end