This code checks for a running Docker container by name and, if found, stops and removes it.
npm run import -- "Restart the docker service"
if docker ps | grep "{name}" then; \
docker stop {name}; \
docker rm {name}; \
fi
bash
#!/bin/bash
# Define a function to stop and remove a container by name
stop_container() {
local name="$1"
# Check if the container exists
if docker ps --format '{{.Names}}' | grep -q "^$name\$"; then
# Stop the container
docker stop "$name"
# Remove the container
docker rm "$name"
else
# TODO: Add logging to notify about non-existent container
echo "Container '$name' not found"
fi
}
# Call the function with the desired container name
stop_container "{name}"
This code snippet checks if a Docker container with a specific name ("{name}") is running and, if so, stops and removes it.
Here's a breakdown:
docker ps | grep "{name}"
:
docker ps
command to list running containers.grep
to search for a line containing the specified container name ("{name}").then;
:
grep
finds a match (meaning the container is running), the code block following the then
statement is executed.docker stop {name};
:
STOP
signal to the container with the specified name.docker rm {name};
:
fi
:
if
statement.In essence, this code provides a concise way to stop and remove a Docker container if it is currently running.