Skip to content

Instantly share code, notes, and snippets.

@bcooksey
Last active August 20, 2020 15:35
Show Gist options
  • Save bcooksey/4e739027746ecee4cd22748e470cc99d to your computer and use it in GitHub Desktop.
Save bcooksey/4e739027746ecee4cd22748e470cc99d to your computer and use it in GitHub Desktop.
dshell: A little wrapper around the docker-compose run command that intelligently gets you a shell inside a container
#!/bin/bash
if [ ! -z $1 ]; then
MATCHER=$1
else
# Try to guess the project based on directory name
MATCHER=`pwd | sed 's/\/.*\///'`
fi
echo "Looking for web container named '$MATCHER'..."
CONTAINER_ID=`docker ps -a -f name=web_run | grep $MATCHER | head -n 1 | cut -d' ' -f1`
#CONTAINER_ID=`docker ps -a -f name=web_run | head -n 2 | tail -n 1 | cut -d' ' -f1`
if [ -z $CONTAINER_ID ]; then
echo "No container exists, creating it (hit enter after a sec to bring up terminal)..."
docker-compose run --service-ports --use-aliases web /bin/bash
exit 0
fi
STATUS=`docker inspect --format='{{json .State.Status}}' $CONTAINER_ID`
echo -n "Found $CONTAINER_ID and it is currently $STATUS. "
if [[ "$STATUS" = '"running"' ]]; then
echo "Shelling in..."
docker exec -i -t $CONTAINER_ID /bin/bash
else
echo "Starting and shelling in..."
docker start $CONTAINER_ID
docker exec -i -t $CONTAINER_ID /bin/bash
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment