How do I compare bash command output and use IF ELSE block to do something.
I am trying to capture the bash command output in CMD variable and if the variable is empty / zero, then output that the binary/feature is missing. Pretty basic.
In the below code, the second if else
# Check if the CPU supports KVM
cmd=$(grep -Eiw 'vmx|svm' /proc/cpuinfo)
if [[ $cmd -ne 0 ]];then
echo "CPU on this machine does not support KVM. Check documentation please"
fi
#!/bin/bash
# Check if KVM kernel modules are installed.
cmd=$(lsmod | awk '{print $1}' | grep -Eiw 'kvm\|kvm_intel\|kvm_amd')
if [[ $cmd -ne 0 ]];then
echo "KVM kernel modules kvm or kvm_[intel|amd] missing. Use modprobe to load them please"
fi
# Check if the CPU supports KVM
cmd=$(grep -Eiw 'vmx|svm' /proc/cpuinfo)
if [[ $cmd -ne 0 ]];then
echo "CPU on this machine does not support KVM. Check documentation please"
fi
Instead of just checking the condition, the script is printing the command output (/proc/cpuinfo), I just want it to print the echo line but not the command output.
grepreturns or what it outputs to stdout? Those are two different things.cmd=$(grep ...)captures the output.grep, Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. If you're checking the exit status, then you're going about it the wrong way. If you want the exit status, then check$?right after executing thegrep. It will have a value of 0 if there was a match. You don't get the exit status usingcmd=$(grep ...).grepagainst a0? The result ofgrep -Eiw 'vmx|svm'...is either going to be one or more lines that containvmxorsvm, or no lines at all. In the case of no lines at all,grepdoes not output a 0.