通过外壳脚本检查响应

时间:2018-12-02 21:57:36

标签: shell scripting centos7

请原谅一个基本问题,但是我没有尝试的想法,并且在编写任何脚本时都是初学者。在关闭虚拟机电源之前,我需要检查虚拟机是否打开。这是我正在尝试的:

(忽略变量,我正在其他几个函数中使用它们,它们都工作正常)

function powerOff(){
    ssh $IP_ADDR 'vim-cmd vmsvc/power.getstate '$VM_ID' | grep Powered'
    if [ "${1}" == "Powered off" ]; then 
        echo "The VM is already off"
    elif [ "${1}" == "Powered on" ]; then
        ssh $CENTOS_IP 'init 0'
    else
        echo "You are horrible at this and your script is failing"
    fi
}

由于我正在抓紧它,因此“ power.getstate”返回“ Powered on”或“ Powered off”。

我正在已运行的VM上对此进行测试,因此我希望响应为“此VM已启动”。相反,我得到了getstate命令的输出(这很好,但我什至不希望看到输出),然后告诉我我对此感到非常恐惧。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

将结果捕获到变量中。

function powerOff(){
    powerfield=$(ssh $IP_ADDR 'vim-cmd vmsvc/power.getstate '$VM_ID' | grep Powered')
    if [ "${powerfield}" == "Powered off" ]; then 
        echo "The VM is already off"
    elif [ "${powerfield}" == "Powered on" ]; then
        ssh $CENTOS_IP 'init 0'
    else
        echo "You are horrible at this and your script is failing"
    fi
}