Walking Through a Python venv Bootstrap Shell Script
System DesignModel answerLast updated
Explain each line of a bash script that builds a Python virtual environment, predict its output and files, and argue why shell automation suits environment setup.
You are handed the following setup script and asked to talk through it as you would with a teammate.
#!/usr/bin/env bash
set -euo pipefail
mkdir -p demo_app
cd demo_app
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install requests
pip freeze > requirements.txt
echo "Ready: $(python --version) at $(which python)"
Answer the following:
- Explain what every line does and why it is there.
- Suppose you save the file as
setup.shand runbash setup.shin a terminal. Describe the output you would see and the files and directories left behind. - Is your terminal still in the virtual environment afterward? Explain why or why not.
- What are the advantages of using a shell script for environment setup and automation, and where does this approach fall short?
State your assumptions (OS, Python version, network access) and mention failure modes you would guard against.
Hints
Hint 1
Go line by line, but group them: interpreter and safety settings, directory creation, venv creation and activation, package installation, and recording and reporting.
Hint 2
Think about which process executes the script when you type `bash setup.sh`. What happens to environment changes such as PATH modifications when that process exits?
Hint 3
For the advantages part, consider repeatability, speed of onboarding, and use in CI, then name limits such as Windows support, unpinned versions, and growing complexity.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Line-by-line explanation
#!/usr/bin/env bash: The shebang. If the file is run as ./setup.sh, the kernel launches whichever bash appears first on PATH. This is more portable than hard-coding /bin/bash.
set -euo pipefail: Strict mode.
-eaborts on the first command that returns non-zero.-umakes use of an unset variable an error, which catches typos.-o pipefailmakes a pipeline fail if any stage fails, not just the last one.
Without it, a failed pip install would still be followed by a cheerful "Ready" message. For automation this is the most valuable line.
mkdir -p demo_app: Creates the project folder. -p suppresses the error if it already exists and creates missing parents, so re-running is safe.
cd demo_app: Everything that follows happens inside the project folder.
python3 -m venv .venv: Runs the standard-library venv module with that specific interpreter, creating an isolated environment in .venv. Using -m ties the environment to the python3 you invoked. The command is silent on success. It writes pyvenv.cfg, a bin/ directory with python links, and bootstraps pip through ensurepip.
source .venv/bin/activate: Runs the activation script in the current shell process. It prepends .venv/bin to PATH, sets VIRTUAL_ENV, defines a deactivate function and usually changes the prompt. From here on, python and pip resolve to the venv's copies.
pip install --upgrade pip: The pip bundled with a venv can be old. Upgrading improves dependency resolution and wheel support.
pip install requests: Installs requests and its dependencies (urllib3, idna, certifi, charset-normalizer) into .venv/lib/python3.X/site-packages, leaving the system Python untouched.
pip freeze > requirements.txt: Writes exact installed versions (for example requests==2.32.3) so someone else can rebuild the same environment with pip install -r requirements.txt.
echo "Ready: $(python --version) at $(which python)": Prints a confirmation. The path should point inside .venv, which proves activation worked.
What running it shows
bash setup.sh prints pip's progress output and nothing for the venv creation step. Roughly:
Requirement already satisfied: pip in ./.venv/lib/python3.12/site-packages (24.0)
Collecting pip
Downloading pip-<newer>-py3-none-any.whl
Successfully installed pip-<newer>
Collecting requests
Downloading requests-<ver>-py3-none-any.whl
Collecting charset-normalizer, idna, urllib3, certifi ...
Successfully installed certifi-... charset-normalizer-... idna-... requests-... urllib3-...
Ready: Python 3.12.x at /home/you/demo_app/.venv/bin/python
Artifacts on disk:
demo_app/
├── requirements.txt # pinned versions, including transitive dependencies
└── .venv/
├── pyvenv.cfg # base interpreter path, version, include-system-site-packages = false
├── bin/ # activate scripts, python, python3, pip, pip3 (Scripts\ on Windows)
├── include/
└── lib/python3.12/site-packages/ # requests and its dependencies
The subtle point: activation does not survive the script
bash setup.sh (or ./setup.sh) starts a child process. The PATH change, VIRTUAL_ENV and the cd all live in that child and vanish when it exits. Back at your prompt, you are not in demo_app and the venv is not active. To get that effect you can:
- activate manually afterward:
source demo_app/.venv/bin/activate, or - source the script itself:
source setup.sh.
Sourcing has side effects. set -e and set -u now apply to your interactive shell, so a single failure can close the terminal, and the cd persists. For that reason, activate manually, or have the script finish by printing an instruction.
Advantages of a shell script for setup
- Reproducibility. Every developer, CI runner and container runs the same steps in the same order, which removes "works on my machine" drift, especially when versions are pinned.
- Brevity. A dozen lines replace a page of README prose. Shell is the natural glue for command-line tools.
- Automation. The same file can be called from a Makefile, a CI job or a Dockerfile
RUN. - Fail-fast behavior. Strict mode stops at the first error rather than leaving a half-built environment.
- Idempotent pieces.
mkdir -pandvenvover an existing directory make re-runs mostly harmless (--clearforces a rebuild). - Executable documentation. New hires can read exactly what the setup does.
Limits and trade-offs
- Bash is not native on Windows; you need WSL, Git Bash or a PowerShell equivalent.
- Branching, error messages and argument parsing become brittle as the script grows.
pip install requestsis unpinned, so two runs on different days can produce different environments. In real projects usepip install -r requirements.txtor a lock file (pip-tools, Poetry, uv).- Tools like
make,tox,uvor Docker give stronger isolation and guarantees at scale.
Failure modes to guard against
python3missing or too old: check withcommand -v python3and validate the version.- Debian/Ubuntu without the
python3-venvpackage:venvfails with anensurepip is not availableerror. - No network or a private package index:
pip installfails andset -ehalts the script. A--index-urloption may be needed. - Paths containing spaces: quote every variable expansion if you parameterize the script.
- Version control: add
.venv/to.gitignoreand commit onlyrequirements.txt, since venvs contain absolute paths and are not relocatable.
Common mistakes in answers
- Reading lines aloud without explaining why they exist.
- Claiming the venv stays active after running the script.
- Forgetting that
pip freezecaptures transitive dependencies too. - Treating shell as always the best tool, with no mention of its limits.
Cost
Runtime is dominated by network downloads and grows roughly with total package size. Disk usage is the venv skeleton plus installed packages, typically tens of megabytes for a small dependency set.