如何在 Bash 中将变量设置为 `docker-compose restart` 命令的输出?

How to set a variable to the output of a `docker-compose restart` command in Bash?

我写一个bash shell 来确定docker-compose updocker-compose restart:

#!/bin/bash
re=$(docker-compose -f prod.yml restart)
echo re:${re}
if [[ -n ${re} && ${re} == *"No containers to restart"* ]];then
  echo -e '\e[0;31;1mNO CONTAINER FOUND. WILL EXEC UP COMMAND...\e[0m'
  docker-compose -f prod.yml up
fi

但是每次我执行这个脚本时,var re 总是空的。脚本的输出是:

ERROR: No containers to restart
re:

有什么方法可以解决这个问题或实现我的目标的其他方法吗?

您可以尝试重定向 stderr 输出。 例如: re=$(docker-compose -f prod.yml restart 2>&1)