在 Bash 脚本中检查已执行命令的结果



我想在登录后运行我的VirtualBox。为此,我必须检查它是否已经在运行。如果没有,请启动 VM。

我的问题是我无法将 VirtualBox 命令的结果放入 Bash 中的变量中。

我创建了一个函数来获取退出参数,但收到"语法错误:参数无效"|">错误消息。

我怎样才能让它工作?

这是我的 Bash 脚本:

########## 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 ##############

为了做你想做的事情,你必须使用命令替换:

check_vm_status="$(VBoxManage showvminfo "om-server" | grep -c "running (since")"

需要注意的是,指令将在变量扩展期间(即在变量分配期间(执行。

如果你只想在函数期间执行你的指令,你可以使用一个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

请注意,eval带来了很多问题。

最新更新