theskumar / theskumar/python-dotenv
`set_key` does not handle single quote `'` inside value properly
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 8.9k
- Forks
- 581
- PR merge metrics
- No merged PRs in 30d
Description
Problem
set_key function does not properly handle single quote ' inside value.
python-dotenv version: 1.0.1
Related PR
- https://github.com/theskumar/python-dotenv/pull/330 (https://github.com/theskumar/python-dotenv/pull/330#discussion_r669439596)
How to reproduce
- Run python script below
- Run
source .env
Python Script
from dotenv import set_key
def main():
var_value = "I'm a bug :("
set_key(".env", "VAR", var_value)
if __name__ == "__main__":
main()
Error from source .env
bash: .env: line 1: syntax error near unexpected token `('
bash: .env: line 1: `VAR='I\'m a bug :(''
Example of fix
⚠️ this fix produces values that dotenv cannot parse (see this issue) ⚠️
from dotenv import set_key
def fixed_set_key(file_path, key, value):
# properly escape ' if present
# https://stackoverflow.com/questions/8254120/how-can-i-escape-a-single-quote-in-a-single-quote-string-in-bash/26165123#26165123
value = value.replace("'", "'\"'\"'")
set_key(file_path, key, f"'{value}'", quote_mode="never")
def main():
var_value = "I'm a fixed :)"
fixed_set_key(".env", "VAR", var_value)
if __name__ == "__main__":
main()
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the set_key entry point and reproduce the issue with the Python script in this report, then source the generated .env file in Bash. Trace how values are quoted and escaped, including the related PR discussion and warning about dotenv parsing. Done means a value containing a single quote is written in a form that both Bash can source and dotenv can parse correctly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100