Skip to content

Instantly share code, notes, and snippets.

@RickyCook
Created August 16, 2022 06:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickyCook/dfcc13846e5b97a4a484e54d3d1ec18f to your computer and use it in GitHub Desktop.
Save RickyCook/dfcc13846e5b97a4a484e54d3d1ec18f to your computer and use it in GitHub Desktop.
Wrap a command in a Docker container to create a simple "in Linux" utility
#!/usr/bin/env bash -e
### CONFIG
CONTAINER_NAME=something_unique_here
CONTAINER_IMAGE=python:3.9 # must have bash, or change the infinite sleep on :17
COMMAND_PREFIX=./pants
### STOP EDITING
THISDIR="$(cd "$(dirname "$0")"; pwd)"
docker container inspect "$CONTAINER_NAME" 2>&1 >/dev/null || docker container create \
--name "$CONTAINER_NAME" \
--volume "$THISDIR:/work" \
"$CONTAINER_IMAGE" \
bash -c 'while true; do sleep 1; done' \
>/dev/null
function on_exit() {
local exit_code=$?
docker container kill "$CONTAINER_NAME" >/dev/null
exit $exit_code
}
trap on_exit EXIT
docker container start "$CONTAINER_NAME" >/dev/null
docker container exec \
--interactive \
--tty \
--workdir /work \
"$CONTAINER_NAME" \
"$COMMAND_PREFIX" "$@"
@sammcj
Copy link

sammcj commented Aug 17, 2022

I think it's best practice to use set -e rather than bash -e as not all environments support more than 1 shebang argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment