Skip to content

Instantly share code, notes, and snippets.

@michael34435
Last active February 6, 2017 06:16
Show Gist options
  • Save michael34435/7a4e5a930d3e4d87186d979342a5a664 to your computer and use it in GitHub Desktop.
Save michael34435/7a4e5a930d3e4d87186d979342a5a664 to your computer and use it in GitHub Desktop.
Close all docker container and execute the command in specified container
#!/bin/bash
function ansi() {
bold=
color=
if [[ -z "$2" ]]; then
color="0"
else
color="$2"
fi
if [[ -z "$3" ]]; then
bold="0"
else
bold="$3"
fi
echo -e "\033[${bold};${color}m$1\033[0;0m"
}
function docker_ps() {
echo "docker=()"
for line in $(docker ps --format "table {{.Names}}")
do
if [[ $line != "NAMES" ]]; then
echo "docker+=(${line})"
fi
done
}
function docker_should_porcess() {
echo "docker=()"
eval $(docker_ps)
for container in ${docker[@]}; do
if [[ $1 != $container ]]; then
echo "docker+=(${container})"
fi
done
}
function docker_check_open() {
eval $(docker_ps)
for container in ${docker[@]}; do
if [[ $1 == $container ]]; then
echo 1
break
fi
done
}
container="$1"
is_open=$(docker_check_open $container)
if [[ -z $is_open ]]; then
ansi "The container you specified is not exists" 31
exit 1
fi
eval $(docker_should_porcess $container)
ansi "Stop another container now" 32
for container in ${docker[@]}; do
docker stop $container
done
ansi "Execute your command" 32
docker exec ${@}
ansi "Retrive container to the previous state" 32
for container in ${docker[@]}; do
docker start $container
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment