Bootstrapping a Reproducible Python Environment with Bash
StringsModel answerLast updated
Write and explain a Bash script that creates or reuses a Python virtual environment and installs dependencies, covering strict mode, idempotency, activation pitfalls, and resulting files.
You are setting up a Python project on a fresh Linux machine and want one command that prepares an isolated environment for it.
Write a short Bash script (or review one you are given) that does the following:
- Creates a virtual environment in a directory chosen by the user, defaulting to
.venv. - Lets the caller override which Python interpreter is used.
- Upgrades
pipinside the environment. - Installs the packages listed in
requirements.txt, but only when that file exists. - Can be run several times without breaking anything.
Then answer the following:
- Walk through your script line by line. What does each command do, and why is it there?
- Why might a script be a better way of doing this than typing commands by hand, following a README, or using another tool? What are its limits?
- Suppose you make the script executable and run it from the project root. What files and directories should appear, and what will and will not change in your current terminal session?
Please be precise about the shebang line, exit-on-error behavior, file permission bits, and what source really does when used inside a script.
Hints
Hint 1
A script runs in a child process. Think about which changes to environment variables survive after that child exits, and how that affects activating a virtual environment.
Hint 2
You do not need to activate an environment to use it: the interpreter inside the environment's `bin` directory already knows where its own packages live.
Hint 3
For idempotency, decide what condition proves that the environment is usable (an existing directory is not enough), and consider what happens on a second run.
Hint 4
Consider strict-mode options such as `set -euo pipefail`, and note where `-e` does not take effect, such as inside `if` conditions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
A good answer shows that you understand what each line does at the OS level, can spot the common trap with activation, and can justify the script as an engineering choice.
A reference script
#!/usr/bin/env bash
# setup_env.sh: create or reuse a project virtual environment
set -euo pipefail
VENV_DIR="${1:-.venv}"
PYTHON_BIN="${PYTHON_BIN:-python3}"
REQ_FILE="requirements.txt"
if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then
echo "error: $PYTHON_BIN not found on PATH" >&2
exit 1
fi
if [ ! -x "$VENV_DIR/bin/python" ]; then
echo "Creating virtual environment in $VENV_DIR"
"$PYTHON_BIN" -m venv "$VENV_DIR"
else
echo "Reusing existing virtual environment in $VENV_DIR"
fi
"$VENV_DIR/bin/python" -m pip install --upgrade pip
if [ -f "$REQ_FILE" ]; then
"$VENV_DIR/bin/python" -m pip install -r "$REQ_FILE"
fi
echo "Done. Activate with: source $VENV_DIR/bin/activate"
Line-by-line explanation
- Shebang (
#!/usr/bin/env bash). When the file is executed directly, the kernel reads the first line and launches that interpreter. UsingenvlocatesbashthroughPATH, which is more portable than hard-coding/bin/bash. The line is just a comment if you runbash script.shorsourcethe file. set -euo pipefail. Strict mode:-eaborts on the first failing command, so a broken install never ends with "Done".-umakes unset variables an error and catches typos.pipefailmakes a pipeline fail if any stage fails.- Caveat:
-eis ignored inifconditions and&&/||lists, so critical checks should be explicit.
- Variables.
${1:-.venv}uses the first argument or falls back to.venv.${PYTHON_BIN:-python3}allowsPYTHON_BIN=python3.12 ./setup_env.sh. Quote every expansion so paths with spaces work. - Interpreter check.
command -vis the POSIX way to test that an executable exists. Output is silenced, the error goes to stderr (>&2), andexit 1gives CI a non-zero status. - Idempotency guard. Testing for an executable
bin/pythonis better than testing for the directory. A half-built or empty directory from an earlier failure is then repaired rather than trusted. - Creation.
python3 -m venv DIRuses the standard library. The third-party alternativevirtualenvis faster and supports older Pythons, but needs installing. On Debian and Ubuntu,venvmay require thepython3-venvpackage. - Installing through the venv's interpreter.
"$VENV_DIR/bin/python" -m pip ...guarantees that the pip used belongs to that environment and that packages go into itssite-packages. No activation is needed. - Conditional requirements install.
-fmakes the script work for brand-new projects with no requirements file. - Final message. Tells the user how to activate, for the reason below.
The source trap
Many candidates put source .venv/bin/activate inside the script. Running ./script.sh starts a child process. Activation changes PATH, VIRTUAL_ENV, and the prompt only in that child, and they vanish when it exits. Your terminal remains unactivated.
Options:
- Call the venv's binaries by explicit path (preferred inside scripts).
- Print an instruction and let the user activate.
- Run the script with
source script.shso it executes in the current shell. The trade-off is thatset -eandexitthen affect your interactive shell and can close it on failure.
Running it and what to expect
chmod +x setup_env.sh # add the execute permission bit
./setup_env.sh # without +x: "Permission denied"
echo $? # 0 on success
Without the execute bit, execve is refused even with a valid shebang, although bash setup_env.sh still works.
Expected result:
.venv/
├── pyvenv.cfg # base Python location, version, system-site-packages = false
├── bin/ # python, python3, pip, activate (+ csh/fish/ps1 variants)
├── include/
└── lib/python3.X/site-packages/ # pip and requirements packages
- pip output prints to the terminal, and downloads are cached under
~/.cache/pip. - Your current shell is unchanged until you run
source .venv/bin/activate. After that,which pythonpoints into.venv/binand the prompt shows(.venv). - A second run prints "Reusing existing virtual environment" and pip reports "Requirement already satisfied".
Why a script rather than alternatives
- Reproducibility. Everyone, including CI, runs the same steps in the same order. A README relies on humans not skipping steps.
- Fail-fast automation. Exit codes plus
set -emake it safe in CI, Dockerfiles, and onboarding tooling. - No extra dependencies. Bash and Python are already present. A Python bootstrap script has a chicken-and-egg problem, and Make, tox, or nox need installing.
- Reviewable. Setup logic lives in version control.
- Parameterizable. Arguments and environment variables serve dev, test, and CI.
Limitations:
- Not portable to native Windows without WSL or Git Bash.
- Shell gets brittle as logic grows.
- A plain
requirements.txtis not fully reproducible. Pin versions and hashes, or use a lock file (pip-tools, Poetry, uv).
Common mistakes
- Relying on
source activateinside the script and expecting the terminal to stay activated. - Checking only that the directory exists, so broken environments are never fixed.
- Forgetting to quote variables.
- Using bare
pip, which may belong to the system Python. - Forgetting
chmod +xand then misreading the "Permission denied" error. - Assuming
set -ecatches every failure, including those insideifconditions.