I want to run my VirtualBox after my I logged in. To do that, I have to check if it’s already running or not. If not, then start the VM.
My problem is that I can not put the result of VirtualBox command into a variable in Bash.
I’ve created a function to get the exit parameter, but I get a “Syntax error: Invalid parameter ‘|'” error message.
How can I make it work?
This is my Bash script:
########## Starting om-server VirtualBox ############## function Run_VM { "$@" local status=$? if [ $status -eq 0 ]; then echo "Starting om-server VM!"; VBoxManage startvm "om-server" sleep 30 ssh root@192.168.1.111 else echo "om-server VM is running!" fi return $status } check_vm_status="VBoxManage showvminfo "om-server" | grep -c "running (since"" Run_VM $check_vm_status ########## Starting om-server VirtualBox ##############
Advertisement
Answer
In order to do what you want, you would have to use command substitution:
check_vm_status="$(VBoxManage showvminfo "om-server" | grep -c "running (since")"
The caveat is that the instructions will be executed during the variable expansion (i.e. during the variable allocation).
If you want to execute your instructions only during your function, you could use a eval
:
function Run_VM { eval "$@" local status=$? if [ $status -eq 0 ]; then echo "Starting om-server VM!"; VBoxManage startvm "om-server" sleep 30 ssh root@192.168.1.111 else echo "om-server VM is running!" fi return $status } check_vm_status="VBoxManage showvminfo "om-server" | grep -c "running (since"" Run_VM $check_vm_status
Note that eval
brings a lot of issues.