Search code examples
pythonlinuxdebian

Why are my environmental variables adding whitespace?


I'm running Debian 12 and Python 3.9.16.

test.env:

export TEST="ABC"
export SECONDTEST="DEF"

I run source test.env

Then try to run this script in Python:

import os

test1 = os.getenv("TEST")
test2 = os.getenv("SECONDTEST")


def printenv(envvar):
    print(envvar)
    for char in envvar:
        print(char)
    print("done")

    if envvar == "ABC" or envvar == "DEF":
        print("ok!")
    else:
        print("Not ok!")


printenv(test1)
printenv(test2)

printenv(test1.rstrip())

The environmental variables add a new line character to the end. The output is:

A
B
C

done
Not ok!
DEF
D
E
F

done
Not ok!
ABC
A
B
C
done
ok!

Why are there newline characters in my environmental variables?


Solution

  • You have MSWin line ends in the test.env script. It means each line ends with a $'\r' which is appended to the value assigned to a variable.

    Run fromdos or dos2unix to fix the CR/LF issue.