Search code examples
bashshelldocker-composestderr

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


I write a bash shell to detemine docker-compose up or docker-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

but each time I exec this script, the var re is always empty. The output of script is:

ERROR: No containers to restart
re:
  • ERROR: No containers to restart is the output of docker-compose -f prod.yml restart

Is there any way to solve this issue or another way to achieve my goal ?


Solution

  • You can try to redirect stderr output. For example: re=$(docker-compose -f prod.yml restart 2>&1)