Issue
Forgive the basic question, but I'm out of ideas to try and I'm a beginner when it comes to scripting anything. I need to check a VM to see if it's on before powering off the VM. Here is what I'm trying:
(ignore the variables, I'm using them in several other functions and they're all working fine)
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
}
The "power.getstate" returns either "Powered on" or "Powered off" since i'm grepping it.
I'm testing this on a VM that is already running, so I want the response to be "This VM is already on". Instead, I'm getting the output of the getstate command (which is fine, but I'd rather not even see the output) and then it tells me I'm horrible at this. Any suggestions?
Solution
Catch the results in a variable.
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
}
Answered By - Walter A Answer Checked By - Clifford M. (WPSolving Volunteer)