Skip to content

Instantly share code, notes, and snippets.

@R3tr0BoiDX
Last active December 31, 2023 00:21
Show Gist options
  • Save R3tr0BoiDX/da04ed0fe0964272a1735474ea5b553f to your computer and use it in GitHub Desktop.
Save R3tr0BoiDX/da04ed0fe0964272a1735474ea5b553f to your computer and use it in GitHub Desktop.
I was tired of cluttering up my system with dependencies and tools that I only needed to use once, for example to compile something. This gives me a temporary environment in Docker, based on Debian. It mounts the current working directory into the container, automatically updates its package index on startup, and deletes itself unless specifical…
#!/bin/bash
# R3tr0Boi 2023
# Function to display usage information
function show_usage {
echo "Usage: $0 [-k] [-h]"
echo "Options:"
echo " -k Keep the container at the end (do not remove)"
echo " -h Display this help screen"
exit 1
}
# Check for command-line options
while getopts ":kh" opt; do
case ${opt} in
k )
keep_container=true
;;
h )
show_usage
;;
\? )
echo "Invalid option: -$OPTARG"
show_usage
;;
esac
done
# Get the absolute path of the current directory
current_dir="$(pwd)"
# Define the base container name
base_container_name="tempenv"
# Generate a unique container name by appending the current Unix timestamp
container_name="$base_container_name-$(date +%s)"
# Create a new Docker container based on Debian
container_id=$(docker run -it -d --name $container_name -v "$current_dir:/mnt" debian:latest)
# Run apt update inside the container
docker exec -it $container_id apt update
# Create a custom bashrc file with colored prompt
docker exec -it $container_id sh -c "echo 'PS1=\"\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ \"' >> /root/.bashrc"
# Enter the console of the container with the working directory set to the mounted directory
docker exec -it -w /mnt $container_id bash
# Optionally, print container ID or remove the container based on user choice
if [ "$keep_container" = true ]; then
echo "Container ID: $container_id"
else
docker stop $container_id
docker rm $container_id
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment