Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
### Fixed

- Strip a leading UTF-8 BOM from `.env` file contents so the first variable is no longer silently lost when the file is saved with BOM (e.g. by some JetBrains IDEs on Windows) by [@h1whelan] in [#640]
- `set_key` now writes values containing `'` using a double-quoted, escaped form so the resulting `.env` line is valid shell and round-trips through the parser (#543)

## [1.2.2] - 2026-03-01

Expand Down
7 changes: 6 additions & 1 deletion src/dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,12 @@ def set_key(
)

if quote:
value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
if "'" in value_to_set:
# a single quote can't be escaped in a single-quoted value; use double quotes
escaped = value_to_set.replace("\\", "\\\\").replace('"', '\\"')
value_out = '"{}"'.format(escaped)
else:
value_out = "'{}'".format(value_to_set)
else:
value_out = value_to_set
if export:
Expand Down
5 changes: 3 additions & 2 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ def test_set_key_no_file(tmp_path):
[
("", "a", "", (True, "a", ""), "a=''\n"),
("", "a", "b", (True, "a", "b"), "a='b'\n"),
("", "a", "'b'", (True, "a", "'b'"), "a='\\'b\\''\n"),
("", "a", "'b'", (True, "a", "'b'"), "a=\"'b'\"\n"),
("", "a", '"b"', (True, "a", '"b"'), "a='\"b\"'\n"),
("", "a", "b'c", (True, "a", "b'c"), "a='b\\'c'\n"),
("", "a", "b'c", (True, "a", "b'c"), 'a="b\'c"\n'),
("", "a", 'b"c', (True, "a", 'b"c'), "a='b\"c'\n"),
("", "a", 'I\'m "in"', (True, "a", 'I\'m "in"'), 'a="I\'m \\"in\\""\n'),
("a=b", "a", "c", (True, "a", "c"), "a='c'\n"),
("a=b\n", "a", "c", (True, "a", "c"), "a='c'\n"),
("a=b\n\n", "a", "c", (True, "a", "c"), "a='c'\n\n"),
Expand Down
Loading