Skip to content

Instantly share code, notes, and snippets.

@zonia3000
Last active August 25, 2019 09:11
Show Gist options
  • Save zonia3000/d9a4e4fb0acae2d3f05239756ffdafa8 to your computer and use it in GitHub Desktop.
Save zonia3000/d9a4e4fb0acae2d3f05239756ffdafa8 to your computer and use it in GitHub Desktop.
Bash function for opening a bash inside a Docker container specifying the image name instead of the id

dockerbash

Why?

When working on a Dockerfile I often need to open a bash inside the generated container in order to check what the Dockerfile has generated.

This requires 3 steps:

  • running docker ps
  • checking the container id that we need (usually based on the image name)
  • running docker exec -i -t <container_id> bash

This script does this in one step: dockerbash <image_name>

How to use

Put in on a directory and load it from your ~/.bashrc

source ~/bash_functions/dockerbash.sh
function dockerbash() {
if [ "$#" -ne 1 ]; then
echo "Usage: dockerbash <image_name>"
return 1
fi
running=`docker ps | grep "$1"`
number=`echo "$running" | wc -l`
if [ -z "$running" ]; then
echo "No container found for $1"
return 1
elif [ "$number" -eq 1 ]; then
id=`echo $running | cut -d" " -f1`
else
echo "Multiple containers found, please specify the id"
echo "$running"
echo -n "Id: "
read id
fi
docker exec -i -t $id bash
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment