Skip to content

Instantly share code, notes, and snippets.

@Skitionek
Created March 1, 2024 12:46
Show Gist options
  • Save Skitionek/87385a0c9530e9186e44291edbc9e89d to your computer and use it in GitHub Desktop.
Save Skitionek/87385a0c9530e9186e44291edbc9e89d to your computer and use it in GitHub Desktop.
How to wrap docker run in bash script
#!/bin/bash
# region Load environment variables from .env file
if [ -f .env ]; then
set -a
source .env
set +a
fi
# endregion
# region Handle SIGINT, SIGTERM, and SIGKILL
# Ussage:
# _term [signal] [container]
_term() {
echo "Caught $1 signal forwarding to docker container $container"
docker kill -s $1 $container
}
_sigint() {
_term SIGINT
}
_sigterm() {
_term SIGTERM
}
_sigkill() {
_term SIGKILL
}
trap _sigint SIGINT
trap _sigterm SIGTERM
trap _sigkill SIGKILL
# endregion
# region helpers
# State helper
# Ussage:
# status [State]
# Example:
# status Running
function status() {
docker container inspect -f "{{.State.${1}}}" $container
}
# Container exists
# Ussage:
# exists
function exist() {
docker container inspect $container > /dev/null 2>&1
}
# endregion
# Here one can put arbitrary set of commands/flags for docker run
container=$(
docker run -d --rm ${@:1}
)
exist &&
docker attach --sig-proxy=false $container &&
exit $(status ExitCode) || exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment