Skip to content

Instantly share code, notes, and snippets.

@appendjeff
Last active December 14, 2016 22:25
Show Gist options
  • Select an option

  • Save appendjeff/91e56dadb8a301cc724fa8b2cf9055c0 to your computer and use it in GitHub Desktop.

Select an option

Save appendjeff/91e56dadb8a301cc724fa8b2cf9055c0 to your computer and use it in GitHub Desktop.
search command to replace the `docker exec -it $container_name /bin/bash` pattern
#!/bin/sh
if [ -z "$1" ]
then
echo 'usage: docker-open $container_name_substring'
echo ''
echo 'Open up bash container given substring found in docker ps'
echo 'Since it greps all of docker ps, you can do:'
echo ' docker-open 801[0-9]'
echo 'and it will give you a menu to jump into one of the containers that is running on port 8010-8019'
exit 1
fi
# Grep everything instead of just docker ps --format '{{.Names}}'
chosen_docker_container=$(docker ps | grep $1 | awk '{print $NF}');
num_containers_matched=$(docker ps | grep $1 | wc -l);
if [ $num_containers_matched -eq 0 ]; then
num_all_containers_matched=$(docker ps -a | grep $1 | wc -l);
if [ $num_all_containers_matched -ne 0 ]; then
echo 'Your container is stopped. Please restart it before opening.'
else
echo 'Could not find the container.'
fi
exit 1
fi
if [ $num_containers_matched -ne 1 ]; then
echo "More than one container found. Please choose a number:"
echo "$(docker ps | grep $1 | awk '{print $NF}' | nl)"
end_sed='q;d';
while true; do
read -p "Which container do you want to bash in? [\d+] " num
case $num in
[0-9]* )
chosen_docker_container="$(docker ps | grep $1 | awk '{print $NF}' | nl | sed $num$end_sed | awk '{print $NF}')"
break
;;
[Nn]* ) exit 1;;
* ) echo "Please type a matching number or 'no' | ctrl-c";;
esac
done
fi
echo $chosen_docker_container
docker exec -it $chosen_docker_container /bin/bash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment