Skip to content

Instantly share code, notes, and snippets.

@etam
Last active December 23, 2017 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etam/d1c7ae9ccb9015b69d2e to your computer and use it in GitHub Desktop.
Save etam/d1c7ae9ccb9015b69d2e to your computer and use it in GitHub Desktop.
wrapper for running commands in docker containers
#!/bin/bash
# usage: _docker_wrapper [--root] image command
user="--user=${UID}"
if [[ "$1" == "--root" ]]; then
user="--user=root"
shift
fi
readonly image="$1"
shift
readonly container="${image//[\/:.]/_}_container"
readonly running="$(docker inspect --format="{{ .State.Running }}" "$container" 2>/dev/null)"
[[ -z "$running" ]] \
&& docker run \
-d \
-e "HOME=$HOME" \
--name "$container" \
-v /etc/passwd:/etc/passwd:ro \
-v /etc/group:/etc/group:ro \
-v "${HOME}:${HOME}" \
-u ${UID}:${GROUPS[0]} \
"$image" \
/bin/sh -c "while true; do sleep 100000; done" \
>/dev/null
[[ "$running" == "false" ]] \
&& docker start "$container" >/dev/null
tty="--tty=false"
if [[ -t 0 && -t 1 ]]; then
tty="--tty=true"
fi
exec docker exec -i "$tty" "$user" "$container" /bin/sh -c "cd \"${PWD}\"; exec \$0 \"\$@\"" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment