Skip to content

Instantly share code, notes, and snippets.

@e7d
Created June 26, 2023 13:43
Show Gist options
  • Save e7d/bd39034362fd21724949077f73def907 to your computer and use it in GitHub Desktop.
Save e7d/bd39034362fd21724949077f73def907 to your computer and use it in GitHub Desktop.
Find a PID running container name
#!/bin/bash
set -e
error() {
echo "Error: $1"
exit 1
}
trap 'error "An unexpected error occurred. Exiting."' ERR
if [ -z "$1" ]; then
echo "Usage: $0 <pid>"
exit 1
fi
CGROUP_PATH=/proc/$1/cgroup
if [ ! -f $CGROUP_PATH ]; then
echo "Process $1 not found"
exit 1
fi
if [ ! -r $CGROUP_PATH ]; then
echo "Permission denied to read $CGROUP_PATH"
exit 1
fi
CONTAINER_ID=$(cat $CGROUP_PATH | grep -o -E '[0-9a-f]{64}' | head -n 1)
if [ -z "$CONTAINER_ID" ]; then
echo "Process $1 is not in a container"
exit 1
fi
CONTAINER_NAME=$(docker inspect --format '{{.Name}}' $CONTAINER_ID | sed 's/^\///')
echo "$CONTAINER_ID: $CONTAINER_NAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment