Skip to content

Instantly share code, notes, and snippets.

@mopa
Last active August 27, 2023 15:08
Show Gist options
  • Save mopa/8be0542f0367a449534b42161b9ee484 to your computer and use it in GitHub Desktop.
Save mopa/8be0542f0367a449534b42161b9ee484 to your computer and use it in GitHub Desktop.
Script for view and copy the internal ip of a docker container
#!/usr/bin/env bash
set -euo pipefail
ID_WIDTH=$(docker ps --format "{{.ID}}" | awk '{ print length }' | sort -nr | head -n 1)
NAME_WIDTH=$(docker ps --format "{{.Names}}" | awk '{ print length }' | sort -nr | head -n 1)
IMAGE_WIDTH=$(docker ps --format "{{.Image}}" | awk '{ print length }' | sort -nr | head -n 1)
print_containers() {
docker ps --format "{{.ID}} {{.Names}} {{.Image}}" | while read -r id name image; do
printf "%-${ID_WIDTH}s \033[36m%-${NAME_WIDTH}s\033[0m %-${IMAGE_WIDTH}s\n" "$id" "$name" "$image"
done
}
SELECTED_CONTAINER=$(print_containers | fzf --prompt="🐳 Docker Container  " --ansi --multi --no-sort --reverse)
SELECTED_CONTAINER_ID=$(echo "$SELECTED_CONTAINER" | awk '{print $1}')
if [ -n "$SELECTED_CONTAINER_ID" ]; then
IP_ADDRESS=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $SELECTED_CONTAINER_ID)
echo "IP address: $IP_ADDRESS"
echo "$IP_ADDRESS" | xclip -selection clipboard
# For MAC OS
# echo "$IP_ADDRESS" | pbcopy
echo "IP address copied to clipboard."
else
echo "No container selected."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment