How to implement common bash idioms in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Many tasks commonly done in Bash — listing files, piping commands, reading environment variables, text processing — have cleaner and more portable equivalents in Python. Python's os, pathlib, subprocess, and shutil modules cover most of what Bash scripts do, with better error handling and cross-platform support. This article maps the most common Bash idioms to their Python equivalents.
Listing and Iterating Over Files
Running Shell Commands
Environment Variables
File Tests (Existence, Type, Size)
Reading and Writing Files
Text Processing (grep, sed, awk)
Copying, Moving, and Deleting Files
Command-Line Arguments
Exit Codes and Error Handling
Common Pitfalls
- Using
os.system()instead ofsubprocess.run():os.system()does not capture output, does not raise on failure, and is vulnerable to shell injection. Always usesubprocess.run()with a list of arguments. - Using
shell=Trueunnecessarily:subprocess.run("ls -l", shell=True)invokes the shell and is a security risk if the command includes user input. Usesubprocess.run(["ls", "-l"])(list form) instead. - Forgetting
text=Truein subprocess: Withouttext=True,subprocess.runreturns bytes (b"output") instead of strings. Addtext=True(orencoding="utf-8") for string output. - Using string concatenation for file paths:
base + "/" + namebreaks on Windows. UsePath(base) / nameoros.path.join(base, name)for portable paths. - Not handling file encoding: Bash reads files as bytes by default. Python 3 opens files as UTF-8 (on most systems). If the file uses a different encoding, pass
encoding="latin-1"or the correct encoding toopen().
Summary
- Use
pathlib.Pathfor file operations — it replacesls,test -f,mkdir, and path manipulation - Use
subprocess.run()with list arguments instead ofos.system()for running commands - Use
os.environ.get()with a default value instead of${VAR:-default} - Use
re.sub()for sed-like substitutions and list comprehensions for grep-like filtering - Use
shutilforcp,mv, andrm -rfequivalents - Use
argparsefor command-line argument parsing instead ofsys.argvfor real scripts
Related reading
- How to implement mini-batch gradient descent in python?
- How to implement negative infinity in Python?
- How to implement pytesseract code with opencl to make it run on GPU?
- How to implement RSI Divergence in Python
- How to implement the ReLU function in Numpy
- How to implement the Softmax function in Python?
- How to implement the Softmax function in Python?
- How to import a Python class that is in a directory above?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.