Forked from jsidhu/gist:2ff16fe4ee734fdf358471ded60c99f4
Last active
June 27, 2024 12:50
-
-
Save mqu/8e204f61712be418ad8458da282d33f9 to your computer and use it in GitHub Desktop.
Prints the name of the container inside which the process with a PID on the host is
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# given a process ID (PID), give me container name | |
# url: https://gist.github.com/mqu/8e204f61712be418ad8458da282d33f9 | |
# forked from : https://gist.github.com/jsidhu/2ff16fe4ee734fdf358471ded60c99f4 | |
# https://stackoverflow.com/questions/24406743/coreos-get-docker-container-name-by-pid | |
# Prints the name of the container inside which the process with a PID on the host is. | |
function getName { | |
local pid="$1" | |
if [[ -z "$pid" ]]; then | |
echo "Missing host PID argument." | |
exit 1 | |
fi | |
if [ "$pid" -eq "1" ]; then | |
echo "Unable to resolve host PID to a container name." | |
exit 2 | |
fi | |
# ps returns values potentially padded with spaces, so we pass them as they are without quoting. | |
local parentPid="$(ps -o ppid= -p $pid)" | |
local containerId="$(ps -o args= -f -p $parentPid | grep containerd-shim-runc-v2 | cut -d ' ' -f 5)" | |
if [[ -n "$containerId" ]]; then | |
local containerName="$(docker inspect --format '{{.Name}}' "$containerId" | sed 's/^\///')" | |
if [[ -n "$containerName" ]]; then | |
echo "$containerName" | |
else | |
echo "$containerId" | |
fi | |
else | |
getName "$parentPid" | |
fi | |
} | |
getName "$1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment